package com.epalmpay.service.weixin.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.epalmpay.entity.profit.Profit;
import com.epalmpay.enumdef.*;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.app.IAppNoticeService;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.weixin.IWxApiService;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.bonus.BonusUserInfoDTO;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.BizEnum.PaymentScene;
import com.epalmpay.enumdef.BizEnum.PaymentType;
import com.epalmpay.enumdef.BizEnum.TransactionStatus;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.AliTkPay;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.IXDLPayAPI;
import com.epalmpay.payplat.WxTkPay;
import com.epalmpay.payplat.XLWxTkPay;
import com.epalmpay.payplat.result.AliTKPayResult;
import com.epalmpay.payplat.result.FyBeQueryResult;
import com.epalmpay.payplat.result.FyBeResult;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.payplat.result.PayWxPayResult;
import com.epalmpay.payplat.result.WxTKPayResult;
import com.epalmpay.payplat.result.XLWxTkPayResult;
import com.epalmpay.payplat.result.XdlTkPayResult;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.posapi.PosApiService;
import com.epalmpay.service.posapi.PosApiServiceTransactional;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxApiWalletService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.usercenter.UserAuthApi;
import com.epalmpay.util.*;
import com.epalmpay.util.Response;
import com.epalmpay.util.code.CodeUtil;
import com.epalmpay.util.code.QRCodeParams;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import com.github.binarywang.wxpay.bean.result.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.util.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service("wxApiWalletService")
public class WxApiWalletServiceImpl implements IWxApiWalletService {

    @Resource
    private GroupConfigMapper groupConfigMapper;
    @Resource
    private WalletInfoMapper walletInfoMapper;
    @Resource
    private BonusVerifyLogMapper bonusVerifyLogMapper;
    @Resource
    private BonusVerifyRuleMapper bonusVerifyRuleMapper;
    @Resource
    private ShopUserMapper shopUserMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private ActivityUnroutineMapper activityUnroutineMapper;
    @Autowired
    private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
    @Resource
    private MallGoodMapper mallGoodMapper;
    @Resource
    private MallGoodCommentMapper mallGoodCommentMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private AgentMapper agentMapper;
    @Resource
    private CouponUserMapper couponUserMapper;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private GroupPayconfigMapper groupPayconfigMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private GroupWxconfigMapper groupWxconfigMapper;
    @Resource
    private OrderServiceGoodMapper orderServiceGoodMapper;
    @Resource
    private OrderServiceGoodDetailMapper orderServiceGoodDetailMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private DeviceDeskCardMapper deviceDeskCardMapper;
    @Resource
    private TradeOfflineMapper tradeOfflineMapper;
    @Resource
    private GroupWxtemplateMapper groupWxtemplateMapper;
    @Resource
    private OrderGoodMapper orderGoodMapper;
    @Resource
    private SysMessageBaseMapper sysMessageBaseMapper;
    @Resource
    private SysMessageInfoMapper sysMessageInfoMapper;
    @Resource
    private YsOilcardOrderMapper oilcardOrderMapper;

    @Resource
    private BonusVerifyShopMapper bonusVerifyShopMapper;

    @Resource
    private GroupReceiveInfoMapper groupReceiveInfoMapper;
    @Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;
    @Resource
    private PrePurchaseActivityMapper prePurchaseActivityMapper;

    @Resource
    private PrePurchaseMoneyChangeMapper prePurchaseMoneyChangeMapper;
    @Resource
    private StatisMemberMapper statisMemberMapper;
    @Resource
    private BonusSendLogMapper bonusSendLogMapper;
    @Resource
    private YsObdPurchaseApplyMapper ysObdPurchaseApplyMapper;

    @Autowired
    protected WxService wxService;
    @Autowired
    protected IWxBaseService wxBaseService;
    @Autowired
    protected PosApiService posApiService;
    @Resource
    private IProfitStatisService profitStatisService;
    @Resource
    private IMemberService memberService;
    @Autowired
    @Lazy
    private ITemplateMailSendService templateMailSendService;

    @Autowired
    private PosApiServiceTransactional posApiServiceTransactional;
    @Resource
    private WxApiMallServiceImpl wxApiMallService;

    @Resource
    private BonusSendRuleMapper bonusSendRuleMapper;

    private ExecutorService exec;

    @Resource
    private IWalletService walletService;

    @Resource
    private IGroupService groupService;

    @Resource
    private MachineWasherMapper machineWasherMapper;

    @Resource
    private ProfitMapper profitMapper;

    @Resource
    TradeWithdrawMapper tradeWithdrawMapper;

    @Resource
    private OrderGoodItemMapper orderGoodItemMapper;

    @Resource
    private MallEntityGoodMapper mallEntityGoodMapper;

    @Resource
    private MallEntityGoodSpecMapper mallEntityGoodSpecMapper;

    @Resource
    private IAppNoticeService appNoticeService;

    @Value("${PROFIT_URL}")
    private String profiturl;

    @Value("${TRADE_FEE}")
    private String tradefee;

    @Value("${PAY.ROOT_HOME_URL}")
    String ROOT_HOME_URL;//项目路径不 带项目名称

    @PostConstruct
    public void initialize() {
        exec = Executors.newCachedThreadPool();
    }

    private Logger logger = LoggerFactory.getLogger(WxApiWalletServiceImpl.class);

    @Override
    public Map<String, Object> getYourLikeShopList(String memberId, String user_longitude, String user_latitude, Integer pageNo, Integer pageSize)
            throws Exception {

        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (pageNo == null) {
            throw new ApplicationException(Rescode.FAIL, "pageNo 不能为空！");
        }
        if (pageSize == null) {
            throw new ApplicationException(Rescode.FAIL, "pageSize 不能为空！");
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Map<String, Object> param = new HashMap<String, Object>();
        // 取得门店数据；
        param.clear();
        param.put("memberId", Long.parseLong(memberId));
        param.put("start", pageSize * (pageNo - 1));
        param.put("limit", pageSize);
        List<Shop> shops = shopMapper.selectYourLikeShop(param);
        List<Map<String, Object>> shopList = new ArrayList<Map<String, Object>>();
        for (Shop shop : shops) {
            Map<String, Object> shopDetail = new HashMap<String, Object>();
            shopDetail.put("shop_id", shop.getId());
            shopDetail.put("shop_ico", shop.getIcon());
            shopDetail.put("shop_name", shop.getMerchantName());
            shopDetail.put("shop_score", shop.getShopScore());
            // shopDetail.put("shop_consume_average",shop.getShopScore());
            shopDetail.put("shop_type", shop.getIndustryName());
            String tolongitude = shop.getLongitude();
            String tolatitude = shop.getLatitude();
            long calDistance = -1;

            if (StringUtil.notEmpty(user_longitude) && StringUtil.notEmpty(user_latitude) && StringUtil.notEmpty(tolongitude)
                    && StringUtil.notEmpty(tolatitude)) {

                calDistance = QqMapApiHelper.getDistance(QqMapApiHelper.MODE_DRIVING, user_latitude, user_longitude, tolatitude, tolongitude);
                if (calDistance < 0) {// 负1的情况下
                    double s = LocationUtils.getDistance(Double.parseDouble(user_latitude), Double.parseDouble(user_longitude), Double.parseDouble(tolatitude),
                            Double.parseDouble(tolongitude));
                    calDistance = (long) s;
                }
                shopDetail.put("shop_location", calDistance);
            } else {
                shopDetail.put("shop_location", calDistance);
            }

            // 取得门店活动列表
            List<ActivityUnroutine> activityUnroutines = activityUnroutineMapper.queryActivityListByShopID(shop.getId());
            List<Map<String, Object>> activityList = new ArrayList<Map<String, Object>>();
            for (ActivityUnroutine activityUnroutine : activityUnroutines) {
                Map<String, Object> activityMap = new HashMap<String, Object>();
                activityMap.put("aitiviate_id", activityUnroutine.getActivityId());
                activityMap.put("aitiviate_type", activityUnroutine.getActivityType());
                activityMap.put("aitiviate_name", activityUnroutine.getActivityName());
                activityList.add(activityMap);
            }
            if (activityList.size() > 0) {
                shopDetail.put("activity_list", activityList);
            }
            shopList.add(shopDetail);
        }
        if (shopList.size() > 0) {
            // 有距离才可以排序
            if (StringUtil.notEmpty(user_longitude) && StringUtil.notEmpty(user_latitude)) {
                shopList = SortUtil.sort(shopList, "shop_location", "asc");
            }
            map.put("shop_list", shopList);
        }

        return map;
    }

    public Map<String, Object> getActivityShopList(String activityId, String user_longitude, String user_latitude) throws Exception {
        if (Tools.isEmpty(activityId)) {
            throw new ApplicationException(Rescode.FAIL, "activityId 不能为空！");
        }
        Map<String, Object> map = new HashMap<String, Object>();

        // 取得门店数据；
        List<Shop> shops = shopMapper.selectActivityAttendShop(Long.parseLong(activityId));
        List<Map<String, Object>> shopList = new ArrayList<Map<String, Object>>();
        for (Shop shop : shops) {
            Map<String, Object> shopDetail = new HashMap<String, Object>();
            shopDetail.put("shop_id", shop.getId());
            shopDetail.put("shop_ico", shop.getIcon());
            shopDetail.put("shop_name", shop.getMerchantName());
            shopDetail.put("shop_score", shop.getShopScore());
            // shopDetail.put("shop_consume_average",shop.getShopScore());
            shopDetail.put("shop_type", shop.getIndustryName());
            String tolongitude = shop.getLongitude();
            String tolatitude = shop.getLatitude();
            long calDistance = -1;
            if (StringUtil.notEmpty(user_longitude) && StringUtil.notEmpty(user_latitude) && StringUtil.notEmpty(tolongitude)
                    && StringUtil.notEmpty(tolatitude)) {
                calDistance = QqMapApiHelper.getDistance(QqMapApiHelper.MODE_DRIVING, user_latitude, user_longitude, tolatitude, tolongitude);
                if (calDistance > 0) {
                    shopDetail.put("shop_location", calDistance);
                } else {
                    double s = LocationUtils.getDistance(Double.parseDouble(user_latitude), Double.parseDouble(user_longitude), Double.parseDouble(tolatitude),
                            Double.parseDouble(tolongitude));
                    shopDetail.put("shop_location", (long) s);
                }
            } else {
                shopDetail.put("shop_location", calDistance);
            }
            shopList.add(shopDetail);
        }
        if (shopList.size() > 0) {
            map.put("shop_list", shopList);
        }
        return map;
    }

    public Map<String, Object> updateWeixinPay(String memberId, String recharge_money, Integer recharge_type, String mchCreateIp) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuffer sb = new StringBuffer();
        // 调用支付平台WeiXin充值接口
        Member member = memberMapper.selectByPrimaryKey(Long.parseLong(memberId));
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
        GroupWxconfig groupWxconfig = groupWxconfigMapper.selectByGroupId(member.getGroupId());
        if (groupWxconfig == null)
            throw new ApplicationException(Rescode.FAIL, sb.append("大商户:(").append(member.getGroupId()).append(")微信未配置!").toString());
        // 插入线下交易表
        TradeOffline record = new TradeOffline();
        record.setMemo("微信线上充值");
        record.setDetail("微信线上充值");// 详情
        record.setTransactionType((byte) BizEnum.TransactionType.Recharge.getType());
        record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
        record.setGroupId(member.getGroupId());
        record.setPayerId(member.getId());// 会员id
        record.setPayerName(member.getName());
        record.setPayerType((byte) CommonEnum.UserType.User.getType());
        record.setReceiverId(memberId);// 接收者id
        record.setReceiverName(member.getName());// 接收者
        record.setReceiverType((byte) CommonEnum.UserType.User.getType());
        record.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        record.setOrderAmount(Integer.valueOf(recharge_money));
        record.setDiscountAmount(0);// 折扣金额
        record.setRealAmount(record.getOrderAmount());// 实付金额
        record.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        record.setIsWallet(true);
        record.setTermSerial(null);
        record.setMerchantNo(null);// 商户号
        record.setTerminalNo(null);// 商户终端号
        record.setTransNo(null); // 交易流水号
        record.setTransOrderNo(null);// 交易机构订单号
        record.setPayAccount("");// 支付卡号
        record.setScanOrganization(null);// 扫码付入网机构
        record.setCrcodeStr(null);
        record.setOldOrderId(null);
        record.setDividableAmount(0);// 可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayBakOrderid(null);
        record.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());// 入网机构
        switch (recharge_type) {
            case 1://普通充值  无赠送
                record.setOrderId(UtilFun.createOrderNum(Const.WECHAT_RECHAREG));
                record.setPayOrderid(UtilFun.createOrderNum(Const.WECHAT_RECHAREG));
                tradeOfflineMapper.insertSelective(record);
                break;
            case 2:
                record.setOrderId(UtilFun.createOrderNum(Const.SEND_RECHARGE));
                record.setPayOrderid(UtilFun.createOrderNum(Const.SEND_RECHARGE));
                tradeOfflineMapper.insertSelective(record);
                ActivityUnroutine activityUnroutine = activityUnroutineMapper.getCurrentRechargeActivite(group.getId(), new Date());
                ActivityUnroutineRule activityUnroutineRule = activityUnroutineRuleMapper.selectActivityUnroutineRuleInfo(activityUnroutine.getActivityId(),
                        Integer.valueOf(recharge_money), (byte) ActivityEnum.BackMoneyMode.Percentage.getType());
                if (activityUnroutineRule != null) {
                    BigDecimal a1 = new BigDecimal(recharge_money);
                    BigDecimal a2 = new BigDecimal(activityUnroutineRule.getFaceValue());// 折扣
                    BigDecimal a3 = a1.multiply(a2);
                    BigDecimal bb3 = new BigDecimal(10000);
                    BigDecimal result = a3.divide(bb3, 2);
                    TradeOffline rradeOffline1 = recordRecharge(member, result.intValue(), record.getId(), activityUnroutine.getActivityId(),
                            UtilFun.createOrderNum());
                    tradeOfflineMapper.insertSelective(rradeOffline1);
                }
                break;
            case 3:
                ActivityUnroutine activity = activityUnroutineMapper.getCurrentRechargeActivite(group.getId(), new Date());
                ActivityUnroutineRule activityU = activityUnroutineRuleMapper.selectActivityUnroutineRuleInfo(activity.getActivityId(),
                        Integer.valueOf(recharge_money), (byte) ActivityEnum.BackMoneyMode.FiexedAmount.getType());
                record.setPayOrderid(UtilFun.createOrderNum(Const.SEND_RECHARGE));
                record.setOrderId(UtilFun.createOrderNum(Const.SEND_RECHARGE));
                tradeOfflineMapper.insertSelective(record);
                if (activityU != null) {
                    TradeOffline rradeOffline2 = recordRecharge(member, activityU.getFaceValue(), record.getId(), activity.getActivityId(),
                            UtilFun.createOrderNum());
                    tradeOfflineMapper.insertSelective(rradeOffline2);
                }
            default:
                break;
        }
        //是否可提现
        String isWithdraw = "0";
        PayWxPayResult payResult = walletService.updateRecharge(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(), record.getPayOrderid(), recharge_money, mchCreateIp,
                groupWxconfig.getWxAppid(), member.getOpenid(), isWithdraw);

        // 返回map
        map.put("sdk_appid", payResult.getJsapi_appid());
        map.put("sdk_timestamp", payResult.getJsapi_timestamp());
        map.put("sdk_noncestr", payResult.getJsapi_noncestr());
        map.put("sdk_package", payResult.getJsapi_package());
        map.put("sdk_signtype", payResult.getJsapi_signtyp());
        map.put("sdk_paysign", payResult.getJsapi_paysign());
        map.put("traderecord", record);
        return map;
    }

    /**
     * @param member
     * @param orderAmount           赠送金额
     * @param relatedTradeOfflineId
     * @param relatedActivityId
     * @return
     */
    public TradeOffline recordRecharge(Member member, Integer orderAmount, Long relatedTradeOfflineId, Long relatedActivityId, String OrgOrderNum) {
        TradeOffline recordRecharge = new TradeOffline();
        recordRecharge.setRelatedTradeOfflineId(relatedTradeOfflineId);// 关联交易记录ID
        recordRecharge.setRelatedActivityId(relatedActivityId);// 关联活动ID
        recordRecharge.setMemo("微信线上充值返现");
        recordRecharge.setDetail("微信线上充值返现");// 详情
        recordRecharge.setTransactionType((byte) BizEnum.TransactionType.RechargeBackCash.getType());
        recordRecharge.setGmtCreate(new Date());
        recordRecharge.setGmtModified(new Date());
        recordRecharge.setGroupId(member.getGroupId());
        recordRecharge.setOrderId(OrgOrderNum);
        recordRecharge.setPayerId(member.getId());// 会员id
        recordRecharge.setPayerName(member.getName());
        recordRecharge.setPayerType((byte) CommonEnum.UserType.User.getType());
        recordRecharge.setReceiverId(member.getId() + "");// 接收者id
        recordRecharge.setReceiverName(member.getName());// 接收者
        recordRecharge.setReceiverType((byte) CommonEnum.UserType.User.getType());
        recordRecharge.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        recordRecharge.setOrderAmount(orderAmount);
        recordRecharge.setDiscountAmount(0);// 折扣金额
        recordRecharge.setRealAmount(orderAmount);// 实付金额
        recordRecharge.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
        recordRecharge.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        recordRecharge.setIsWallet(true);
        recordRecharge.setTermSerial(null);
        recordRecharge.setMerchantNo(null);// 商户号
        recordRecharge.setTerminalNo(null);// 商户终端号
        recordRecharge.setTransNo(null); // 交易流水号
        recordRecharge.setTransOrderNo(null);// 交易机构订单号
        recordRecharge.setPayAccount("");// 支付卡号
        recordRecharge.setScanOrganization(null);// 扫码付入网机构
        recordRecharge.setCrcodeStr(null);
        recordRecharge.setOldOrderId(null);
        recordRecharge.setDividableAmount(0);// 可分润金额
        recordRecharge.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        recordRecharge.setPayOrderid(OrgOrderNum);
        recordRecharge.setPayBakOrderid(null);
        recordRecharge.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());// 入网机构
        return recordRecharge;
    }


    public Response updateWeixinPayConsumption(String memberId, String recharge_money, String mchCreateIp,
                                               String orgOrderNum, String homeRootUrl, String notifyUrl) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuffer sb = new StringBuffer();
        Member member = memberMapper.selectByPrimaryKey(Long.parseLong(memberId));
        Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
        GroupWxconfig groupWxconfig = groupWxconfigMapper.selectByGroupId(member.getGroupId());
        if (groupWxconfig == null)
            throw new ApplicationException(Rescode.FAIL, sb.append("大商户:(").append(member.getGroupId()).append(")微信未配置!").toString());
        WxTkPay wxTkPay = null;
        OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectOrderServiceGoodInfo(orgOrderNum, BizEnum.ServiceOrderStatus.WaitingForPay.getType());
        if (orderServiceGood == null) {
            throw new ApplicationException(Rescode.FAIL, "商品信息不存在");
        }
        MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());
        if (mallGood == null) {
            throw new ApplicationException(Rescode.FAIL, "商品信息不存在");
        }
        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderIdStatus(orgOrderNum, (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        if (tradeOffline == null) {
            throw new ApplicationException(Rescode.FAIL, "未查询到未支付的订单");
        }

        if (tradeOffline.getRealAmount() > 0) {

            GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(group.getId());
            if (groupReceiveInfo == null) {
                throw new ApplicationException(Rescode.FAIL, "收款商户未配置");
            }
            String merchantNo = groupReceiveInfo.getMerchantCode();

            wxTkPay = WxTkPay.initialize(tradeOffline.getRealAmount() + "", null,
                    mchCreateIp, member.getPhone(), notifyUrl, merchantNo, "微信卡劵购买", "00000000", member.getOpenid(), tradeOffline.getOrderId());

            tradeOffline.setReceiverId(group.getId().toString());
            tradeOffline.setReceiverName(group.getMerchantName());
            tradeOffline.setReceiverType((byte)CommonEnum.UserType.BusinessManager.getType());

            tradeOffline.setOrderId(wxTkPay.getOutOrderNum());
            tradeOffline.setMerchantNo(merchantNo);
            tradeOffline.setPayOrderid(wxTkPay.getOutOrderNum());
            tradeOffline.setMemo("微信消费购买");
            tradeOffline.setDetail("微信消费购买");// 详情
            tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
            tradeOffline.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
            tradeOffline.setScanOrganization((byte) BizEnum.ScanInNetCompany.fuqianla.getType());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
        } else {
            Date date = new Date();
            List<String> arrayListCode = GenerateCouponCode(mallGood, tradeOffline, orderServiceGood, date);
            //进行核销 这个订单对应优惠券和积分
            //核销积分优惠券
            if (tradeOffline.getBonusValue() != null && tradeOffline.getBonusValue() > 0) {
                bonusVerifyLogMapper.confirmBonusVerify(tradeOffline.getId());
                memberMapper.updateActualConsumeBonus(tradeOffline.getMemberId(), tradeOffline.getBonusAmount());
            }
            if (tradeOffline.getDiscountAmount() != null && tradeOffline.getDiscountAmount() > 0) {
                couponUserMapper.updateVerifyUserCouponByOrderId2(tradeOffline.getId());
                //跟新这个优惠券已核销张数
                CouponUser couponUser = couponUserMapper.queryCouponIdByTradeId(tradeOffline.getId());
                couponMapper.updateCouponInfo(couponUser.getCouponId());
            }
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
            if(tradeOffline.getDiscountAmount() !=null && tradeOffline.getDiscountAmount()>tradeOffline.getOrderAmount()){
                tradeOffline.setDiscountAmount(tradeOffline.getOrderAmount());
            }
            tradeOffline.setReceiverId(group.getId().toString());
            tradeOffline.setReceiverName(group.getMerchantName());
            tradeOffline.setReceiverType((byte)CommonEnum.UserType.BusinessManager.getType());

            tradeOffline.setPayType((byte) PaymentType.WebChat.getType());
            tradeOffline.setIsWallet(true);// 钱包交易
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            map.put("orderDate", DateUtil.fomatDate(new Date(), DateUtil.sdfTime));
            map.put("orderStateName", BizEnum.TransactionStatus.Success.getName());
            map.put("arrayListCode", arrayListCode);
            map.put("orderId", orgOrderNum);
            map.put("status", 1);
            try {
                templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template4.getType(), tradeOffline.getPayerId(),
                        tradeOffline.getGroupId(), BizEnum.PaymentType.Wallet.getType(), homeRootUrl);
            } catch (Exception e) {
                logger.info("模板消息发送失败" + e);
            }
            return Response.getSuccess(map);
        }

        WxTKPayResult wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
        if (!wxTKPayResult.getResult_code().equals("000000")) {
            throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
        }
        map.put("sdk_appid", wxTKPayResult.getSdk_appid());
        map.put("sdk_timestamp", wxTKPayResult.getSdk_timestamp());
        map.put("sdk_noncestr", wxTKPayResult.getSdk_noncestr());
        map.put("sdk_package", wxTKPayResult.getSdk_package());
        map.put("sdk_signtype", wxTKPayResult.getSdk_signtype());
        map.put("sdk_paysign", wxTKPayResult.getSdk_paysign());
        map.put("orderId", java.net.URLEncoder.encode(tradeOffline.getOrderId()));
        return Response.getSuccess(map);
    }

    /**
     * 钱包支付提交 生成订单号
     */
    @Override
    public Map<String, Object> updateWalletpaydisplay(Long memberId, String goodsId, String goodsPrice, String amount, Integer bonus, String couponSns) throws ApplicationException {
        // Integer
        // orderAmount=Integer.valueOf(goodsPrice)*Integer.valueOf(amount);
        Map<String, Object> map = new HashMap<String, Object>();
        Member member = memberMapper.selectByPrimaryKey(memberId);
        if (member == null || (bonus != null && bonus > member.getBonusAmount())) {
            throw new ApplicationException(Rescode.FAIL, "参数不合法");
        }

        MallGood mallGood = mallGoodMapper.selectByPrimaryKey(Long.valueOf(goodsId));
        if (mallGood == null) {
            throw new ApplicationException(Rescode.FAIL, "商品信息不存在");
        }

        //判断指定会员对指定商品是否超出限购数量
        if (mallGood.getLimitNumber() > 0) {
            int memberHavePurchaseNum = orderServiceGoodMapper.countMemberHavePurchase(memberId, mallGood.getId());
            if (memberHavePurchaseNum + Integer.parseInt(amount) > mallGood.getLimitNumber()) {
                map.put("ErrorMsg", mallGood.getName() + "超出限购数量，请重新选择");
                return map;
            }
        }

        Integer orderAmount = mallGood.getPromotionPrice() * Integer.valueOf(amount);
        //优惠券合法性判断
        String[] couponSnsArray = null;
        Integer couponCoverAmount = 0;
        if (couponSns != null && !Tools.isEmpty(couponSns)) {
            couponSnsArray = couponSns.split(",");
            if (couponSnsArray.length > 1) {
            } else {
                CouponUser couponUser = couponUserMapper.selectByCouponSn(couponSnsArray[0]);
                if (couponUser != null) {
                    if (couponUser.getLimitAmount() > orderAmount) {
                        return null;
                    } else {
                        couponCoverAmount = couponUser.getFaceValue();
                    }
                }
            }
        }

        BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());

        int bonusCoveredMoney = 0;
        if (bonus != null) {
            bonusCoveredMoney = new BigDecimal(bonus).divide(new BigDecimal(bonusVerifyRule.getVerifyRate()), 2, BigDecimal.ROUND_FLOOR)
                    .multiply(new BigDecimal(100)).intValue();
        }

        Date date = new Date();
        // 商品订单
        String orderNo = UtilFun.createOrderNum(Const.CONSUMPTION_VIRTUAL);
        OrderServiceGood orderServiceGood = new OrderServiceGood();
        orderServiceGood.setGroupId(mallGood.getGroupId());
        orderServiceGood.setOrderNo(orderNo);
        orderServiceGood.setMemberId(Long.valueOf(memberId));
        orderServiceGood.setGoodId(Long.valueOf(goodsId));
        orderServiceGood.setGoodName(mallGood.getName());
        orderServiceGood.setNumber(Short.parseShort(amount));
        orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForPay.getType());
        orderServiceGood.setAllVerifyTime(null);
        orderServiceGood.setPayTime(null);
        orderServiceGood.setGmtCreate(date);
        orderServiceGood.setGmtModified(date);
        orderServiceGoodMapper.insert(orderServiceGood);

        TradeOffline tradeOffline = new TradeOffline();
        tradeOffline.setGmtCreate(date);
        tradeOffline.setGmtModified(date);
        tradeOffline.setGroupId(mallGood.getGroupId());
        tradeOffline.setOrderId(orderNo);
        tradeOffline.setPayerId(memberId);// 付款者id号
        tradeOffline.setPayerName(member.getName());// 付款者姓名
        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverId(null);// 接收者id
        tradeOffline.setReceiverName(null);// 接收者 此处以核销录入数据
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());// 交易类型
        tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        tradeOffline.setOrderAmount(orderAmount); // 订单金额
        tradeOffline.setDiscountAmount(bonusCoveredMoney + couponCoverAmount);// 折扣金额
        if (orderAmount - bonusCoveredMoney - couponCoverAmount > 0) {
            tradeOffline.setRealAmount(orderAmount - bonusCoveredMoney - couponCoverAmount);// 实付金额
        } else {
            tradeOffline.setRealAmount(0);// 实付金额
        }
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());// 交易状态
        tradeOffline.setIsWallet(false);
        tradeOffline.setGoodType(null);// 商品类型(线上用) ？
        tradeOffline.setMemo("优惠券购买");
        tradeOffline.setDetail("用户微信公众号购买优惠券");
        tradeOffline.setMerchantNo(null);// 商户号(对账用)
        tradeOffline.setTerminalNo(null);// 商户终端号
        tradeOffline.setPayAccount("");// 支付卡号
        tradeOffline.setScanOrganization(null);// 扫码付入网机构
        tradeOffline.setCrcodeStr(null);
        tradeOffline.setOldOrderId(null);
        tradeOffline.setDividableAmount(0);// 可分润金额
        tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        tradeOffline.setPayOrderid(null);
        tradeOffline.setPayBakOrderid(null);
        tradeOffline.setInNetCompany(null);// 入网机构
        tradeOffline.setPayType((byte) BizEnum.PaymentType.Other.getType());//支付方式
        tradeOfflineMapper.insertSelective(tradeOffline);

        //积分锁定
        if (bonus != null && bonus > 0) {
            int x = memberMapper.updateMemberBonusLock(memberId, bonus);
            if (x == 1) {
                BonusVerifyLog bonusVerifyLog = new BonusVerifyLog();
                bonusVerifyLog.setAdjustAmount(bonus);
                bonusVerifyLog.setAdjustStatus(ActivityEnum.BonusVerityStatus.Locked.getType());
                bonusVerifyLog.setAdjustValue(bonusCoveredMoney);
                bonusVerifyLog.setMemberId(memberId);
                bonusVerifyLog.setGmtCreate(date);
                bonusVerifyLog.setGmtModified(date);
                bonusVerifyLog.setOrderId(tradeOffline.getId());
                bonusVerifyLogMapper.insertSelective(bonusVerifyLog);
            } else {
                throw new ApplicationException("订单创建失败");
            }
        }

        //优惠券锁定
        if (couponSns != null && couponSnsArray != null) {
            for (int p = 0; p < couponSnsArray.length; p++) {
                int z = couponUserMapper.updateLockCoupons(memberId, null, date, tradeOffline.getId(), couponSnsArray[p]);
                if (z != 1) {
                    throw new ApplicationException("订单创建失败");
                }
            }
        }

        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("createDare", sdfTime.format(date));
        map.put("orderState", BizEnum.TransactionStatus.WaitingForPay.getType());
        map.put("orderStateName", BizEnum.TransactionStatus.WaitingForPay.getName());
        map.put("goodsName", mallGood.getName());
        map.put("amount", amount);
        map.put("goodsPrice", orderAmount);
        map.put("orderId", orderNo);
        return map;
    }

    /**
     * 生成商品订单及劵码
     *
     * @param mallGood
     * @param tradeOffline1
     * @param orderServiceGood
     * @param date
     * @return
     */
    public List<String> GenerateCouponCode(MallGood mallGood, TradeOffline tradeOffline1, OrderServiceGood orderServiceGood, Date date) {
        String code1 = Tools.getRandomNum(2);
        List<String> arrayListCode = new ArrayList<>();
        int serviceGoodCount = orderServiceGood.getNumber();

        //
        Map<String, Integer> coupCodeInfo = couponUserMapper.selectSettdAmountBytradeOfflineId(tradeOffline1.getId());
        int coupCodeSettedAmount = SysUtils.Object2int(coupCodeInfo.get("setted_value"));
        int priceValue = SysUtils.Object2int(coupCodeInfo.get("priceValue"));
        logger.debug("GenerateCouponCode....", "coupCodeSettedAmount.." + coupCodeSettedAmount + "....." + priceValue);
        for (short i = 0; i < serviceGoodCount; i++) {
            // 生成劵码
            OrderServiceGoodDetail orderServiceGoodDetail = new OrderServiceGoodDetail();
            orderServiceGoodDetail.setOrderId(orderServiceGood.getId());
            String couponCode = code1 + Tools.getRandomNum(10);
            arrayListCode.add(couponCode);
            orderServiceGoodDetail.setCouponCode(couponCode);// 生成12位随机劵码
            //实际交易金额 除以数量

            if (tradeOffline1.getRealAmount() % serviceGoodCount != 0 && 0 == i) {
                orderServiceGoodDetail.setPrice(tradeOffline1.getRealAmount() / serviceGoodCount + tradeOffline1.getRealAmount() % serviceGoodCount);
            } else {
                orderServiceGoodDetail.setPrice(tradeOffline1.getRealAmount() / serviceGoodCount);
            }
            //商品的原价和卖价存反的
            //mallGood.getPromotionPrice() 表示卖价
            orderServiceGoodDetail.setOriginalPrice(mallGood.getSalePrice());//原始价格     settlement_rate
            // 0:门店;1:总部)
            if (mallGood.getWalletSettleMode() == 1) {
                orderServiceGoodDetail.setSettingPrice(0);
            } else if (mallGood.getWalletSettleMode() == 0) {
                BigDecimal original = new BigDecimal(mallGood.getPromotionPrice());
                BigDecimal discount = new BigDecimal(mallGood.getSettlementRate());
                BigDecimal cypher = original.multiply(discount);
                BigDecimal scale = new BigDecimal(10000);
                BigDecimal result = cypher.divide(scale, 1);
                
                // 查看这笔订单使用的优惠券 需要结算结算金额，如果大于就均分到每个券码
                int merchantValue = (priceValue - coupCodeSettedAmount); //商户需要承担的费用
                if (merchantValue % serviceGoodCount != 0 && 0 == i) {
                    logger.info("===result.intValue()=="+result.intValue());
                    logger.info("===merchantValue=="+merchantValue);
                    logger.info("===serviceGoodCount=="+serviceGoodCount);

                    int settingPrice = result.intValue() - (merchantValue / serviceGoodCount + merchantValue % serviceGoodCount);
                    settingPrice=  Integer.parseInt(String.valueOf(Math.round(settingPrice * (1 - 0.006))));
                    orderServiceGoodDetail.setSettingPrice(settingPrice);
//                    orderServiceGoodDetail.setSettingPrice(result.intValue() - (merchantValue / serviceGoodCount + merchantValue % serviceGoodCount));//结算金额
                } else {

                    logger.info("===result.intValue()=="+result.intValue());
                    logger.info("===merchantValue=="+merchantValue);
                    logger.info("===serviceGoodCount=="+serviceGoodCount);
                    int settingPrice=result.intValue() - (merchantValue / serviceGoodCount);
                    settingPrice=  Integer.parseInt(String.valueOf(Math.round(settingPrice * (1 - 0.006))));
                    orderServiceGoodDetail.setSettingPrice(settingPrice);//结算金额
//                    orderServiceGoodDetail.setSettingPrice(result.intValue() - (merchantValue / serviceGoodCount));//结算金额
                }

            }
            orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.UnVerified.getType());
            orderServiceGoodDetail.setVerifyTime(null);
            orderServiceGoodDetail.setShopId(null);
            orderServiceGoodDetail.setPosId(null);
            orderServiceGoodDetail.setPosName(null);
            orderServiceGoodDetail.setIsCorrect(false);
            orderServiceGoodDetail.setGmtCreate(date);
            orderServiceGoodDetail.setGmtModified(null);
            orderServiceGoodDetailMapper.insert(orderServiceGoodDetail);
        }
        orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
        orderServiceGood.setPayTime(date);
        orderServiceGood.setGmtModified(date);
        orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);
        // 销售数量做累加处理
        int number = (short) orderServiceGood.getNumber();
        if (mallGood.getSaleNum() == null) {
            mallGood.setSaleNum(number);
        } else {
            mallGood.setSaleNum(mallGood.getSaleNum() + number);
        }
        mallGoodMapper.updateByPrimaryKey(mallGood);
        return arrayListCode;
    }

    /***
     * 计算使用的优惠券，的结算金额
     * @param
     * @return
     */


    @Override
    public Map<String, Object> updateWalletpaySubmit(String memberId, String orderId, String payType, String payPwd, String homeRootUrl) throws ApplicationException {
        Member member = memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        if (payType.equals("1")) {
            String OrgOrderNum = UtilFun.createOrderNum(Const.CONSUMPTION_VIRTUAL);
            Date date = new Date();

            if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
                throw new ApplicationException(Rescode.FAIL, "支付密码错误");
            }

            OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectOrderServiceGoodInfo(orderId, BizEnum.ServiceOrderStatus.WaitingForPay.getType());
            if (orderServiceGood != null) {
                MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());
                if (mallGood == null) {
                    throw new ApplicationException(Rescode.FAIL, "商品信息不存在");
                }
                TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderIdStatus(orderId, (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
                if (tradeOffline == null) {
                    throw new ApplicationException(Rescode.FAIL, "订单信息不存在");

                }

                // 调用支付平台消费接口
                if (tradeOffline.getRealAmount() > 0) {
//					String SysTraceNum = DateUtil.getSdfTimes() + Tools.getRandomNum(4);
                    Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
//					PayConsumption cons = PayConsumption.initialize(member.getVirtualCard(), payPwd, SysTraceNum, group.getPayGroupCode(),
//							DateUtil.fomatDate(new Date(), DateUtil.sdfTimes), OrgOrderNum, tradeOffline.getRealAmount() + "", "156", null);
//					PayResult payResult = IPayAPI.consumption(cons);
//					if (!payResult.getRespCode().equals("0000")) {
//						throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
//					}
                    PayResult payResult = walletService.updatePayConsumption(member.getVirtualCard(), group.getPayGroupCode(),
                            member.getUserId(), tradeOffline.getRealAmount(), OrgOrderNum, payPwd, null, orderId);
                    if (!payResult.getRespCode().equals("0000")) {
                        throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
                    }
                    tradeOffline.setTransOrderNo(payResult.getOrderId());
                } else {

                    tradeOffline.setTransOrderNo(null);

                }
                if (orderServiceGood.getGroupId() != null) {

                    Group group = groupMapper.selectByPrimaryKey(orderServiceGood.getGroupId());
                    tradeOffline.setReceiverId(orderServiceGood.getGroupId().toString());// 交易状态
                    tradeOffline.setReceiverName(group.getMerchantName());// 支付平台订单号
                    tradeOffline.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());// 支付平台订单号
                }

                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
                tradeOffline.setPayOrderid(OrgOrderNum);// 支付平台订单号
                tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
                tradeOffline.setIsWallet(true);// 钱包交易

                //优惠券金额大于订单金额
                logger.info("========优惠券金额大于订单金额========");
                if(tradeOffline.getDiscountAmount()!=null &&tradeOffline.getDiscountAmount()>tradeOffline.getOrderAmount()){
                    tradeOffline.setDiscountAmount(tradeOffline.getOrderAmount());
                }

                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                //生成商品订单及劵码
                List<String> arrayListCode = GenerateCouponCode(mallGood, tradeOffline, orderServiceGood, date);

                //进行核销 这个订单对应优惠券和积分
                //核销积分优惠券
                if (tradeOffline.getBonusValue() != null && tradeOffline.getBonusValue() > 0) {
                    bonusVerifyLogMapper.confirmBonusVerify(tradeOffline.getId());
                    memberMapper.updateActualConsumeBonus(tradeOffline.getMemberId(), tradeOffline.getBonusAmount());
                }
                if (tradeOffline.getDiscountAmount() != null && tradeOffline.getDiscountAmount() > 0) {
                    couponUserMapper.updateVerifyUserCouponByOrderId2(tradeOffline.getId());
                    //跟新这个优惠券已核销张数
                    CouponUser couponUser = couponUserMapper.queryCouponIdByTradeId(tradeOffline.getId());
                    couponMapper.updateCouponInfo(couponUser.getCouponId());
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("orderDate", DateUtil.fomatDate(date, DateUtil.sdfTime));
                map.put("orderStateName", BizEnum.TransactionStatus.Success.getName());
                map.put("arrayListCode", arrayListCode);
                map.put("orderId", orderId);
                map.put("tradeOffline", tradeOffline);
                try {
                    templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template4.getType(), tradeOffline.getPayerId(),
                            tradeOffline.getGroupId(), BizEnum.PaymentType.Wallet.getType(), homeRootUrl);
                } catch (Exception e) {
                    logger.info("模板消息发送失败" + e);
                }
                return map;
            } else {
                throw new ApplicationException(Rescode.FAIL, "未发现待付款的订单");
            }
        }
        return null;
    }

    @Override
    public Member selectMemberInfo(Long groupId, String phone, String openId) {
        System.out.println("selectMemberInfo..." + phone + "...." + openId);
        Member member = null;
        if (StringUtils.isNotBlank(phone)) {
            member = memberMapper.selectByPrimaryPhone(groupId, phone, null);
        }

        if (member == null && StringUtils.isNotBlank(openId)) {
            member = memberMapper.selectOpenId(openId, groupId);
        }

        return member;
    }


    @Override
    public Response updateTkWxPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String deskcardId, String remark, String deskcardCode,
                                  String openId, Integer actualTranAmt, Integer nooffertranAmt, String couponCodes, Integer bonusAmount, String rootHomeUrl, String frontUrl) throws ApplicationException {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByPrimaryKey(Long.valueOf(deskcardId));
        Long groupId = device.getGroupId();
        // 会员和非会员走不同的通道
        String fyMerchantCD = null;
        Member member = selectMemberInfo(groupId, phone, openId);
        Integer actualMoney = tranAmt;
        Map<String, Integer> selectTranAmt = new HashMap<String, Integer>();
        if (member != null && actualTranAmt != null) {
            fyMerchantCD = deviceDeskCard.getDeskcardMemMerchantCode();
            selectTranAmt = calActualMoney(phone, tranAmt, nooffertranAmt, couponCodes, bonusAmount, member, device.getShopId(), groupId);
            actualMoney = selectTranAmt.get("realMoney");
            if (!actualTranAmt.equals(actualMoney)) {
                throw new ApplicationException(Rescode.FAIL, "实付金额不一致" + selectTranAmt);
            }
        } else {
            fyMerchantCD = deviceDeskCard.getDeskcardMerchantCode();
        }
        Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
        // 插入线下交易表
        TradeOffline record = finishInitTradeOff(groupId, BizEnum.PaymentType.WebChat, member, shop, deskcardCode, fyMerchantCD, deviceDeskCard);
        //初始化金额相关
        Integer pointCoverAmount = selectTranAmt.get("pointCoverAmount");
        initTradeAmt(record, tranAmt, actualMoney, selectTranAmt.get("couponCoverMoney"), bonusAmount, pointCoverAmount);
        if (actualMoney == 0) {
            String orgOrderNum = Const.TK_DEVICE+UtilFun.createOrderNum();
            record.setOrderId(orgOrderNum);
            record.setPayOrderid(orgOrderNum);
            return finishZroeAmount1(member, shop, record, phone, nooffertranAmt, couponCodes, rootHomeUrl);

        } else {

            if (deviceDeskCard.getDeskcardOrganization() == (byte) BizEnum.DeskCardInNetCompany.fuqianla.getType()) {
                WxTkPay wxTkPay = WxTkPay.initialize(actualMoney + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "微信台卡支付", deskcardCode, openId, UtilFun.createOrderNum(Const.TK_DEVICE));
                WxTKPayResult wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
                if (!wxTKPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
                }
                StringBuffer detail = new StringBuffer();
                detail.append("&appId=").append(wxTKPayResult.getSdk_appid()).append("&timeStamp=").append(wxTKPayResult.getSdk_timestamp()).append("&nonceStr=")
                        .append(wxTKPayResult.getSdk_noncestr()).append("&package=").append(wxTKPayResult.getSdk_package()).append("&signType=")
                        .append(wxTKPayResult.getSdk_signtype()).append("&paySign=").append(wxTKPayResult.getSdk_paysign());
                record.setOrderId(wxTkPay.getOutOrderNum());
                record.setDetail(detail.toString());// 详情
                record.setCrcodeStr(wxTKPayResult.getQr_code());
                record.setTransOrderNo(wxTKPayResult.getMchnt_order_no());
                record.setPayOrderid(wxTkPay.getOutOrderNum());
                tradeOfflineMapper.insertSelective(record);
                //锁定积分 和优惠券
                finishActualMoney(phone, couponCodes, member, device.getShopId(), groupId, nooffertranAmt, record);

                HashMap<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("appId", wxTKPayResult.getSdk_appid());
                resultMap.put("timeStamp", wxTKPayResult.getSdk_timestamp());
                resultMap.put("nonceStr", wxTKPayResult.getSdk_noncestr());
                resultMap.put("package", wxTKPayResult.getSdk_package());
                resultMap.put("signType", wxTKPayResult.getSdk_signtype());
                resultMap.put("paySign", wxTKPayResult.getSdk_paysign());
                if (record != null) {
                    resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
                }
                if (member != null) {
                    resultMap.put("memberId", member.getId() == null ? "" : member.getId());
                }
                if (shop != null) {
                    resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
                }
                return Response.getSuccess(resultMap);

            } else if (deviceDeskCard.getDeskcardOrganization() == (byte) BizEnum.DeskCardInNetCompany.xunlina.getType()) {
                String goodsDes = "用户迅联境外台卡消费";
//					String mchntCd="S001737";
//					String termId="21935";
                String mchntCd = deviceDeskCard.getDeskcardMerchantCode();
                String termId = deskcardCode;

                String transCurrency = "HKD"; // HKD   JPY
                String paymentBrand = "WXP";//  WXP ALP    api/pay/tkPayNotify

                String orderId = UtilFun.createOrderNum(Const.XLTK_DEVICE);
                XLWxTkPay xLWxTkPay = new XLWxTkPay(mchntCd, termId, transCurrency, paymentBrand, actualMoney + "",
                        orderId, mchCreateIp, notifyUrl, frontUrl, goodsDes, remark);
                XLWxTkPayResult xLWxTkPayResult = IPayAPI.finishWxPreCreateTkPay(xLWxTkPay);
                if (!xLWxTkPayResult.getRespCode().equals("00")) {
                    throw new ApplicationException(Rescode.FAIL, "微信调用失败" + xLWxTkPayResult.getErrorDetail());
                }
                record.setOrderId(orderId);
                record.setDetail(xLWxTkPayResult.getErrorDetail());// 详情
                record.setCrcodeStr(xLWxTkPayResult.getH5payURL());
                record.setTransOrderNo(orderId);
                record.setPayOrderid(orderId);
                tradeOfflineMapper.insertSelective(record);

                //锁定积分 和优惠券
                finishActualMoney(phone, couponCodes, member, device.getShopId(), groupId, nooffertranAmt, record);

                HashMap<String, Object> resultMap = new HashMap<String, Object>();

                resultMap.put("h5payURL", xLWxTkPayResult.getH5payURL());
                if (record != null) {
                    resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
                }
                if (member != null) {
                    resultMap.put("memberId", member.getId() == null ? "" : member.getId());
                }
                if (shop != null) {
                    resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
                }
                return Response.getSuccess(resultMap);

            } else if (deviceDeskCard.getDeskcardOrganization() == (byte) BizEnum.DeskCardInNetCompany.xindalu.getType()) {//新大陆支付
                String mchntCd = deviceDeskCard.getDeskcardMerchantCode();
                String termId = deskcardCode;
                String orderId = UtilFun.createOrderNum(Const.XDLTK_DEVICE);
                XdlTkPayResult xdlTkPayResult = IXDLPayAPI.barpospay(mchntCd, termId, orderId, actualMoney + "", actualMoney + "", "WXPAY", "新大陆微信台卡支付");

                if (!xdlTkPayResult.getResult().equals("S")) {
                    throw new ApplicationException(Rescode.FAIL, "微信调用失败" + xdlTkPayResult.getMessage());
                }
                record.setOrderId(orderId);
                record.setDetail(xdlTkPayResult.getResult());// 详情
                record.setCrcodeStr(xdlTkPayResult.getPayCode());
                record.setTransOrderNo(orderId);
                record.setPayOrderid(orderId);
                tradeOfflineMapper.insertSelective(record);
                //锁定积分 和优惠券
                finishActualMoney(phone, couponCodes, member, device.getShopId(), groupId, nooffertranAmt, record);
                HashMap<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("h5payURL", xdlTkPayResult.getPayCode());
                if (record != null) {
                    resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
                }
                if (member != null) {
                    resultMap.put("memberId", member.getId() == null ? "" : member.getId());
                }
                if (shop != null) {
                    resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
                }
                return Response.getSuccess(resultMap);
            } else {
                throw new ApplicationException(Rescode.FAIL, "未查询到该台卡支付类型");
            }
        }

    }


    @Override
    public Response updateTkAliPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String deskcardId, String remark, String deskcardCode,
                                   Integer actualTranAmt, Integer nooffertranAmt, String couponCodes, Integer bonusAmount, String rootHomeUrl) throws ApplicationException {
        logger.info("方法开始时间" + DateUtil.getTime());
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByPrimaryKey(Long.valueOf(deskcardId));

        Long groupId = device.getGroupId();
        // 会员和非会员走不同的通道
        String fyMerchantCD = null;

        Member member = selectMemberInfo(groupId, phone, null);
        Integer actualMoney = tranAmt;
        Map<String, Integer> selectTranAmt = new HashMap<String, Integer>();
        if (member != null && actualTranAmt != null) {
            fyMerchantCD = deviceDeskCard.getDeskcardMemMerchantCode();
            // 实付金额
            selectTranAmt = calActualMoney(phone, tranAmt, nooffertranAmt, couponCodes, bonusAmount, member, device.getShopId(), groupId);
            actualMoney = selectTranAmt.get("realMoney");

            logger.info("------------------" + actualTranAmt);
            logger.info("===================" + actualMoney);
            if (!actualTranAmt.equals(actualMoney)) {
                throw new ApplicationException(Rescode.FAIL, "实付金额不一致");
            }
        } else {
            fyMerchantCD = deviceDeskCard.getDeskcardMerchantCode();
        }
        Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
        TradeOffline record = finishInitTradeOff(groupId, BizEnum.PaymentType.AliPay, member, shop, deskcardCode, fyMerchantCD, deviceDeskCard);
        //初始化金额相关
        Integer pointCoverAmount = selectTranAmt.get("pointCoverAmount");

        initTradeAmt(record, tranAmt, actualMoney, selectTranAmt.get("couponCoverMoney"), bonusAmount, pointCoverAmount);
        // 插入线下交易表
        if (actualMoney > 0) {
            if (deviceDeskCard.getDeskcardOrganization() == (byte) BizEnum.DeskCardInNetCompany.fuqianla.getType()) {

                logger.info("支付宝请求开始时间" + DateUtil.getTime());
                AliTkPay aliTkPay = AliTkPay.initialize(actualMoney + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "支付宝台卡充值", (UtilFun.createOrderNum(Const.TK_DEVICE)), deskcardCode);
                AliTKPayResult aliTKPayResult = IPayAPI.finishAliTkPay(aliTkPay);
                logger.info("支付宝请求结束时间" + DateUtil.getTime());
                if (!aliTKPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL, "支付宝调用失败" + aliTKPayResult.getResult_msg());
                }
                record.setDetail(aliTKPayResult.getQr_code());// 详情   mchnt_order_no
                record.setCrcodeStr(aliTKPayResult.getQr_code());
                record.setPayOrderid(aliTkPay.getOutOrderNum());
                record.setOrderId(aliTkPay.getOutOrderNum());
                record.setTransOrderNo(aliTKPayResult.getMchnt_order_no());// 交易机构订单号
                tradeOfflineMapper.insertSelective(record);
                //锁定积分和优惠券
                finishActualMoney(phone, couponCodes, member, device.getShopId(), groupId, nooffertranAmt, record);
                logger.info("锁定积分和优惠券 结束时间" + DateUtil.getTime());
                HashMap<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("qr_code", aliTKPayResult.getQr_code());
                if (record != null) {
                    resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
                }
                if (member != null) {
                    resultMap.put("memberId", member.getId() == null ? "" : member.getId());
                }
                if (shop != null) {
                    resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
                }
                logger.info("方法结束时间" + DateUtil.getTime());
                return Response.getSuccess(resultMap);
            } else if (deviceDeskCard.getDeskcardOrganization() == (byte) BizEnum.DeskCardInNetCompany.xindalu.getType()) {//新大陆支付
                String mchntCd = deviceDeskCard.getDeskcardMerchantCode();
                String termId = deskcardCode;
                String orderId = UtilFun.createOrderNum(Const.XDLTK_DEVICE);
                XdlTkPayResult xdlTkPayResult = IXDLPayAPI.barpospay(mchntCd, termId, orderId, actualMoney + "", actualMoney + "", "ALIPAY", "新大陆支付宝台卡支付");

                if (!xdlTkPayResult.getResult().equals("S")) {
                    throw new ApplicationException(Rescode.FAIL, "支付宝调用失败" + xdlTkPayResult.getMessage());
                }
                record.setOrderId(orderId);
                record.setDetail(xdlTkPayResult.getResult());// 详情
                record.setCrcodeStr(xdlTkPayResult.getPayCode());
                record.setTransOrderNo(orderId);
                record.setPayOrderid(orderId);
                tradeOfflineMapper.insertSelective(record);
                //锁定积分 和优惠券
                finishActualMoney(phone, couponCodes, member, device.getShopId(), groupId, nooffertranAmt, record);
                HashMap<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("h5payURL", xdlTkPayResult.getPayCode());
                if (record != null) {
                    resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
                }
                if (member != null) {
                    resultMap.put("memberId", member.getId() == null ? "" : member.getId());
                }
                if (shop != null) {
                    resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
                }
                return Response.getSuccess(resultMap);
            } else {
                throw new ApplicationException(Rescode.FAIL, "未查询到该台卡支付类型");
            }


        } else {
            String orgOrderNum = UtilFun.createOrderNum();
            record.setPayOrderid(orgOrderNum);
            record.setOrderId(orgOrderNum);
            return finishZroeAmount1(member, shop, record, phone, nooffertranAmt, couponCodes, rootHomeUrl);
        }

    }

    private void initTradeAmt(TradeOffline record, Integer tranAmt, Integer actualMoney, Integer cubonsAmount, Integer bonusAmount, Integer pointCoverAmount) {
        record.setOrderAmount(tranAmt); // 订单金额
//        record.setDiscountAmount(cubonsAmount == null ? 0 : cubonsAmount);// 折扣金额
        if(cubonsAmount != null && cubonsAmount>tranAmt){
            record.setDiscountAmount(tranAmt);// 折扣金额
        }else{
            record.setDiscountAmount(cubonsAmount == null ? 0 : cubonsAmount);// 折扣金额
        }
        record.setRealAmount(actualMoney);// 实付金额
        record.setBonusAmount(bonusAmount == null ? 0 : bonusAmount);
        record.setBonusValue(pointCoverAmount == null ? 0 : pointCoverAmount);
    }

    /**
     * @param groupId
     * @param paymentType
     * @param member
     * @param shop
     * @param deskcardCode   商户终端号
     * @param fyMerchantCD   商户号
     * @param deviceDeskCard 扫码付入网机构
     * @return
     */
    private TradeOffline finishInitTradeOff(Long groupId, PaymentType paymentType, Member member, Shop shop, String deskcardCode, String fyMerchantCD, DeviceDeskCard deviceDeskCard) {
        TradeOffline record = new TradeOffline();
        if (member != null) {
            record.setPayerId(member.getId());// 会员id
            record.setPayerName(member.getName());
            record.setPayerType((byte) CommonEnum.UserType.User.getType());
        }

        if (shop != null) {
            record.setReceiverId(shop.getId() + "");// 接收者id
            record.setReceiverName(shop.getMerchantName());// 接收者
            record.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        }

        record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
        record.setGroupId(groupId);
        record.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        record.setSubType((byte) BizEnum.PaymentScene.DeskCard.getType());// 支付场景
        if (BizEnum.PaymentType.AliPay.equals(paymentType)) {
            record.setPayType((byte) BizEnum.PaymentType.AliPay.getType());
            record.setMemo("台卡支付宝支付");
            record.setIsWallet(true);
        } else if (BizEnum.PaymentType.WebChat.equals(paymentType)) {
            record.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
            record.setMemo("台卡微信支付");
            record.setIsWallet(true);
        } else {
            record.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
            record.setMemo("台卡钱包支付");
            record.setIsWallet(false);
        }

        record.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());


        record.setTermSerial(deskcardCode);
        record.setMerchantNo(fyMerchantCD);// 商户号
        record.setTerminalNo(deskcardCode);// 商户终端号
        record.setTransNo(null); // 交易流水号
        record.setPayAccount("");// 支付卡号
        if (deviceDeskCard != null) {
            record.setScanOrganization(deviceDeskCard.getDeskcardOrganization());// 扫码付入网机构
            record.setInNetCompany(deviceDeskCard.getDeskcardOrganization());// 入网机构
        }
        record.setOldOrderId(null);
        record.setDividableAmount(0);// 可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayBakOrderid(null);


        return record;
    }

    //无需支付的时候
    private Response finishZroeAmount1(Member member, Shop shop, TradeOffline record, String phone, Integer nooffertranAmt, String couponCodes, String rootHomeUrl) throws ApplicationException {
        try {
            //锁定积分
            record.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());

            tradeOfflineMapper.insertSelective(record);

            //锁定积分和优惠券
            finishActualMoney(phone, couponCodes, member, shop.getId(), member.getGroupId(), nooffertranAmt, record);
            //完成 积分和优惠券的核销
            posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(record, couponCodes, shop.getId());

        } catch (ApplicationException e1) {

            e1.printStackTrace();
            throw e1;
        }

        //会员门店关系
        posApiService.memberShopRelation(member.getId(), shop.getId(), new Date(), record.getOrderAmount());
        //计算新的会员权益
        posApiService.saveSynNewBenefitCalc(shop.getId(), record.getRealAmount(), member.getGroupId(), member, record.getPayOrderid(), record.getId());


        try {
            templateMailSendService.sendTemplate(record, BizEnum.WebTemplateType.template11.getType(), record.getPayerId(),
                    record.getGroupId(), BizEnum.PaymentType.Wallet.getType(), rootHomeUrl);
        } catch (Exception e) {
            logger.info("模板消息发送失败" + e);
        }
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (record != null) {
            resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
        }
        if (member != null) {
            resultMap.put("memberId", member.getId() == null ? "" : member.getId());
        }
        if (shop != null) {
            resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
        }
        return Response.getSuccessExtend(resultMap, record);
//		return Response.getSuccess(2, "支付成功");
    }


    @Override
    public Boolean updateRechargeOrderState(String orderNo, String transResult, String rootHomeUrl) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (transResult.equals("1") && tradeOffline != null
                && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());

            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            //增加2.0钱包余额
            walletService.updateRechargeNotify(tradeOffline.getPayerId(), tradeOffline.getRealAmount(), 0, "1", tradeOffline.getOrderId());
            //判断充值是否分润
            Group group = groupService.selectGroupInfo(tradeOffline.getGroupId());
            try {
                if (group.getIsRechange() == 1) {
                    profitStatisService.oneOrderProfitCalculate(tradeOffline, tradeOffline.getRealAmount());
                }
                templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template2.getType(), tradeOffline.getPayerId(),
                        tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
            } catch (Exception e) {
                logger.info("充值模板消息发送失败" + e);
            }
            return true;
        } else {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return false;
        }
    }


    @Override
    public Boolean updateAppRechargeOrderState(String orderNo, String transResult) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (transResult.equals("1") && tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return true;
        } else {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
            tradeOffline.setMemo("支付失败");
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return false;
        }
    }


    @Override
    public Boolean updateSendOrderState(String orderNo, String transResult, String rootHomeUrl) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (transResult.equals("1") && tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());

            //根据订单号查询充值送订单号
            TradeOffline tradeOfflineRelated = tradeOfflineMapper.selectRelatedTradeOfflineId(tradeOffline.getId(), (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
            Integer sendtranAmt = null;
            if (tradeOfflineRelated != null) {
                sendtranAmt = tradeOfflineRelated.getRealAmount();
                tradeOfflineRelated.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOfflineRelated);
            }
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);


            //增加2.0钱包余额  充值送的金额 都不可提现
            walletService.updateRechargeNotify(tradeOffline.getPayerId(), tradeOffline.getRealAmount(), sendtranAmt, "0", tradeOffline.getOrderId());
            try {
                //判断充值是否分润
                Group group = groupService.selectGroupInfo(tradeOffline.getGroupId());
                if (group.getIsRechange() == 1) {
                    profitStatisService.oneOrderProfitCalculate(tradeOffline, tradeOffline.getRealAmount());
                    //判断充值者的上级是否是代理
                    Member member = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
                    if (member.getFromType() == BizEnum.MemberDevelopeFrom.AgentDevelope.getType()) {
                        Date date = new Date();
                        Profit profit = new Profit();
                        profit.setGmtCreate(date);
                        profit.setGmtModified(date);
                        profit.setGroupId(group.getId());
                        profit.setProfitType(ProfitEnum.ProfitType.Transaction.getType());

                        profit.setProduceShopid(Long.parseLong(tradeOffline.getReceiverId()));
                        profit.setProduceMemberid(tradeOffline.getPayerId());

                        //查询分润比例
                        GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(tradeOffline.getGroupId());
                        //
                        Integer first_fee_rate = 0;

                        //如果有效期时间大于修改时间且交易月分
                        String tradeMonth = DateUtil.fomatDate(tradeOffline.getGmtCreate(), DateUtil.sdfDayss);
                        if (groupConfig.getValidTime() != null && groupConfig.getValidTime().compareTo(groupConfig.getGmtModified()) > 0
                                && tradeMonth.equals(DateUtil.fomatDate(groupConfig.getGmtModified(), DateUtil.sdfDayss))) {
                            //取老值
                            first_fee_rate = groupConfig.getOldFirstFeeRate() == null ? 0 : groupConfig.getOldFirstFeeRate();
                        } else {
                            first_fee_rate = groupConfig.getFirstFeeRate() == null ? 0 : groupConfig.getFirstFeeRate();
                        }

                        profit.setProfit(tradeOffline.getRealAmount() * first_fee_rate);
                        profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
                        profit.setOrderId(tradeOffline.getId());
                        profit.setOrderNo(tradeOffline.getOrderId());

                        profitMapper.insert(profit);
                    }
                }
                templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template2.getType(), tradeOffline.getPayerId(),
                        tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
            } catch (Exception e) {
                logger.info("充值模板消息发送失败" + e);
            }
            try {
                templateMailSendService.sendTemplate(tradeOfflineRelated, BizEnum.WebTemplateType.template6.getType(), tradeOfflineRelated.getPayerId(),
                        tradeOfflineRelated.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
            } catch (Exception e) {
                logger.info("充值送模板消息发送失败" + e);
            }

            return true;
        } else {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return false;
        }
    }

    @Override
    public TradeOffline updateTkOrderState(String outOrderNum, String orderNo, String transResult, String homeRootUrl) throws ApplicationException {

        logger.info("---------------------------ffff-------------------" + outOrderNum);

        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(outOrderNum);
        if (transResult.equals("1")) {
            logger.info("---------------------------a-------------------");

            if (!tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
                try {
                    memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 活动 送劵
                // 送红包 receiver_id order_amount
                Member member = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
                if (StringUtils.isNotBlank(tradeOffline.getReceiverId()) && member != null) {
                    Long shopId = Long.valueOf(tradeOffline.getReceiverId());
                    if (tradeOffline.getReceiverType() == CommonEnum.UserType.Store.getType()) {
                        posApiService.memberShopRelation(member.getId(), shopId, tradeOffline.getGmtCreate(), tradeOffline.getOrderAmount());

                    }
                    posApiService.saveSynNewBenefitCalc(shopId, tradeOffline.getRealAmount(), tradeOffline.getGroupId(), member, orderNo, tradeOffline.getId());
                    //完成 积分和优惠券的核销
                    posApiServiceTransactional.saveVerifyCouponBonus(tradeOffline, shopId);

                }
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOffline.setTransOrderNo(orderNo);
                //优惠券抵扣金额大于订单金额
                if(tradeOffline.getDiscountAmount() !=null && tradeOffline.getDiscountAmount()>tradeOffline.getOrderAmount()){
                    tradeOffline.setDiscountAmount(tradeOffline.getOrderAmount());
                }

                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                logger.info("------------------------b----------------------");
                //如果是洗衣机订单 发送指令
                if (outOrderNum.startsWith(Const.XYJ_DEVICE)) {
                    try {
                        if (!IPayAPI.sendCommand("start", tradeOffline.getTerminalNo(), tradeOffline.getMarked() + "", tradeOffline.getPayerId() + "", outOrderNum)) {
                            //微信发送模板消息
                            if (tradeOffline.getPayerId() != null) {
                                try {
                                    templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template5.getType(),
                                            tradeOffline.getPayerId(),
                                            tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), ROOT_HOME_URL);
                                } catch (Exception e) {
                                    logger.info("模板消息发送失败" + e);
                                }
                            }
                            //退款
                            posApiService.refundBenefit(tradeOffline, tradeOffline.getTransOrderNo());
                            posApiServiceTransactional.saveOtherRefund(tradeOffline.getTransOrderNo(),
                                    null, tradeOffline.getPayType() != null ? tradeOffline.getPayType() : 0,
                                    tradeOffline);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


                try {
                    templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template11.getType(), tradeOffline.getPayerId(),
                            tradeOffline.getGroupId(), null, homeRootUrl);
                } catch (Exception e) {
                    logger.info("--微信模板发送失败");
                }
                return tradeOffline;
            }
        } else {
            //支付失败，这个 积分 和优惠券 还原
            if (tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.WaitingForPay.getType())) {

                couponUserMapper.updateUnlockCouponOnMember(tradeOffline.getOrderId());
                couponUserMapper.updateUnlockCouponOnNoMember(tradeOffline.getOrderId());
                bonusVerifyLogMapper.updateStatusByOrderId(tradeOffline.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());
                memberMapper.updateMemberBonusUnlock(tradeOffline.getPayerId(), tradeOffline.getBonusAmount());
                tradeOffline.setGmtModified(new Date());
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            }

        }

        return null;
    }

    @Override
    public TradeOffline updateYcgOrderState(String outOrderNum, String orderNo, String transResult, String homeRootUrl) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(outOrderNum);
        if (transResult.equals("1") && tradeOffline != null
                && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            try {
                memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
            Member member = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
            if (StringUtils.isNotBlank(tradeOffline.getReceiverId()) && member != null) {
                Long shopId = Long.valueOf(tradeOffline.getReceiverId());
                if (tradeOffline.getReceiverType() == CommonEnum.UserType.Store.getType()) {
                    posApiService.memberShopRelation(member.getId(), shopId, tradeOffline.getGmtCreate(), tradeOffline.getOrderAmount());
                }
                posApiService.saveSynNewBenefitCalc(shopId, tradeOffline.getRealAmount(), tradeOffline.getGroupId(), member, orderNo, tradeOffline.getId());
            }
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            // 如果当前订单 是预采购订单
            if ("Prepurchase".equals(tradeOffline.getMemo())) {
                finishProcessPrePurchase(tradeOffline);
            }
            tradeOffline.setTransOrderNo(orderNo);
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            if (homeRootUrl != null) {
                try {
                    templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template11.getType(), tradeOffline.getPayerId(),
                            tradeOffline.getGroupId(), null, homeRootUrl);
                } catch (Exception e) {
                    logger.info("--微信模板发送失败");
                }
            }

            //如果当笔交易 收款到大商户变更大商户收款的
            finishUpdateGroupReceiveInfo(tradeOffline);
            return tradeOffline;
        } else {
            return null;
        }
    }

    @Override
    public TradeOffline updateObdOrderState(String orderNo, String transResult) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectOutTradeNo(orderNo, (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        if (transResult.equals("1") && tradeOffline != null
                && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            String orderId = tradeOffline.getOrderId();
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            String orderNoId = orderId.substring(0, orderId.length() - 4);
            List<TradeOffline> listBatch = tradeOfflineMapper.selectByOrderIdBatch(orderNoId, (byte) BizEnum.TransactionStatus.Success.getType(), orderId);
            // 截取获取obd主键ID
            String obdId = orderId.substring(orderId.indexOf("D") + 1, orderId.lastIndexOf("Y"));
            YsObdPurchaseApply ysObdPurchaseApply = ysObdPurchaseApplyMapper.selectByPrimaryKey(Long.valueOf(obdId));
            if (listBatch.size() == 0) {
                ysObdPurchaseApply.setStatus(YunStreamEnum.OBDPurchaseStatus.WaitingForDistribute.getType());
                ysObdPurchaseApplyMapper.updateByPrimaryKey(ysObdPurchaseApply);
            } else {
                ysObdPurchaseApply.setStatus(YunStreamEnum.OBDPurchaseStatus.Paying.getType());
                ysObdPurchaseApplyMapper.updateByPrimaryKey(ysObdPurchaseApply);
            }

            finishUpdateGroupReceiveInfo(tradeOffline);
            return tradeOffline;
        } else {
            return null;
        }
    }

    /**
     * 当前收款
     *
     * @param tradeOffline
     */
    private void finishUpdateGroupReceiveInfo(TradeOffline tradeOffline) {
        try {
            GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectReceiceInfo(tradeOffline.getGroupId(), tradeOffline.getMerchantNo());
            if (groupReceiveInfo != null) {
                if (groupReceiveInfo.getLastTradeDate() != null) {
                    String tradeYyyyMM = DateUtil.fomatDate(tradeOffline.getGmtCreate(), DateUtil.sdfDayss);
                    if (DateUtil.fomatDate(groupReceiveInfo.getLastTradeDate(), DateUtil.sdfDayss).equals(tradeYyyyMM)) {
                        groupReceiveInfo.setLastTradeDate(tradeOffline.getGmtModified());
                        groupReceiveInfo.setTradeAmountPerMonth(tradeOffline.getRealAmount() + groupReceiveInfo.getTradeAmountPerMonth());
                        groupReceiveInfoMapper.updateByPrimaryKey(groupReceiveInfo);
                        return;
                    }
                }
                groupReceiveInfo.setLastTradeDate(tradeOffline.getGmtModified());
                groupReceiveInfo.setTradeAmountPerMonth(tradeOffline.getRealAmount() * 1L);
                groupReceiveInfoMapper.updateByPrimaryKey(groupReceiveInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理预采购相关逻辑
     *
     * @param tradeOffline
     */
    private void finishProcessPrePurchase(TradeOffline tradeOffline) {

        PrePurchaseActivity prePurActivity = prePurchaseActivityMapper.selectByPrimaryKey(tradeOffline.getPrepurActivityId());
        Integer amount = tradeOffline.getOrderAmount();
        prePurActivity.setCustomerSaleAmount(prePurActivity.getCustomerSaleAmount() + tradeOffline.getOrderAmount());
        prePurActivity.setCustomerPayAmount(prePurActivity.getCustomerPayAmount() + tradeOffline.getRealAmount());
        prePurActivity.setCustomerSaleCount(prePurActivity.getCustomerSaleCount() + 1);
        String lastTradeDate = SysUtils.formatDate(prePurActivity.getLastTradeDate(), "yyyyMMDD");
        Integer merchantSetAmount = amount * prePurActivity.getAgentBenefitAmount() / 100;
        prePurActivity.setLastTradeDate(tradeOffline.getGmtCreate());
        // 设置分润
        String tradeDateStr = SysUtils.formatDate(tradeOffline.getGmtCreate(), "yyyyMMDD");
        tradeOffline.setDividableAmount(
                (prePurActivity.getCustomerBenefitAmount() - prePurActivity.getAgentBenefitAmount()) * amount / 100);
        tradeOffline.setShopFee(tradeOffline.getShopFee());
        if (lastTradeDate.equals(tradeDateStr)) {
            // 表示是同一天交易
            prePurActivity.setMerchantTodayAmount(prePurActivity.getMerchantTodayAmount() + merchantSetAmount);

        } else {
            //
            prePurActivity.setMerchantLastDayAmount(prePurActivity.getMerchantTodayAmount());
            prePurActivity.setMerchantTodayAmount(merchantSetAmount);
        }
        prePurActivity.setRiskAmount(prePurActivity.getRiskAmount() + merchantSetAmount);
        System.out.println("merchantSetAmount:" + merchantSetAmount);
        prePurActivity.setGmtModified(new Date());

        if (prePurActivity.getCustomerSaleAmount() >= prePurActivity.getPrepurchaseAmount()) {
            // 这个预采购额度已经满了 ，将他结束
            prePurActivity.setEndDate(new Date());
            prePurActivity.setStatus(BizEnum.PrePurchaseActivityStatus.end.getType());
            ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(prePurActivity.getGroupId(), prePurActivity.getShopId());
            shopGroupRelation.setPrePurchaseStatus(0);//处于预采购模式
            shopGroupRelation.setGmtModified(new Date());
            shopGroupRelationMapper.updateByPrimaryKey(shopGroupRelation);
        }
        // 查询 代理商

        Agent agent = agentMapper.selectByPrimaryKey(prePurActivity.getAgentId());
        PrePurchaseMoneyChange prePurchaseMoneyChange = new PrePurchaseMoneyChange();
        prePurchaseMoneyChange.setAgentId(agent.getId());
        prePurchaseMoneyChange.setAmount(merchantSetAmount * 1L);
        prePurchaseMoneyChange.setChangeType(1);
        prePurchaseMoneyChange.setGmtCreate(new Date());
        prePurchaseMoneyChange.setGmtModified(new Date());
        prePurchaseMoneyChange.setGroupId(agent.getGroupId());
        String balanceStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance()) / 100, 2);
        String moneyStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney()) / 100, 2);
        prePurchaseMoneyChange
                .setInfoDesc("预采购活动进行中，用户消费返还可以约，返还前余额" + balanceStr + ",返还前余额额度为" + moneyStr + ",返还金额为" + SysUtils.formatNumber(merchantSetAmount / 100, 2));
        prePurchaseMoneyChange.setOperateUser("系统处理");
        prePurchaseMoneyChange.setOperateUserId(0L);
        prePurchaseMoneyChange.setType(1);// 表示渠道调整
        prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);

        agent.setPrePurchaseBalance(agent.getPrePurchaseBalance() + merchantSetAmount);
        String descMoney = SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
        agent.setPrePurchaseBalanceDes(descMoney);
        agentMapper.updateByPrimaryKey(agent);

        //
        String merchantNo = tradeOffline.getMerchantNo();

        GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectReceiceInfo(agent.getGroupId(), merchantNo);
        Date tradeDate = groupReceiveInfo.getLastTradeDate();
        if (tradeDate != null && tradeDateStr.startsWith(SysUtils.formatDate(tradeDate, "yyyyMM"))) {
            // 表示是同一天交易
            groupReceiveInfo.setTradeAmountPerMonth(groupReceiveInfo.getTradeAmountPerMonth() + amount);
        } else {
            groupReceiveInfo.setTradeAmountPerMonth(amount * 1L);
        }
        prePurchaseActivityMapper.updateByPrimaryKey(prePurActivity);
    }


    @Override
    public Boolean updateGoodsOrderState(String orderNo, String transResult) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (transResult.equals("1") && tradeOffline != null
                && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            // 查询是否商品订单信息
            OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForPay.getType());
            if (orderGood == null) {
                throw new ApplicationException(Rescode.FAIL, "商品订单信息不存在");
            }
            orderGood.setPayTime(new Date());
            orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());
            orderGoodMapper.updateByPrimaryKey(orderGood);
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            //核销积分优惠券
            if (tradeOffline.getBonusValue() != null && tradeOffline.getBonusValue() > 0) {
                bonusVerifyLogMapper.confirmBonusVerify(tradeOffline.getId());
                memberMapper.updateActualConsumeBonus(tradeOffline.getMemberId(), tradeOffline.getBonusAmount());
            }
            if (tradeOffline.getDiscountAmount() != null && tradeOffline.getDiscountAmount() > 0) {
                couponUserMapper.updateVerifyUserCouponByOrderId2(tradeOffline.getId());
            }

            try {
                profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
                memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
            } catch (Exception e) {
                e.printStackTrace();
                throw new ApplicationException(Rescode.FAIL, "分润交易异常");
            }
            return true;
        } else {

            OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForPay.getType());
            if (orderGood != null) {
                orderGood.setPayTime(new Date());
                orderGood.setStatus(BizEnum.MallOrderStatus.closed.getType());
                orderGoodMapper.updateByPrimaryKey(orderGood);
            }

            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
            tradeOffline.setMemo("支付失败");
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            return false;
        }

    }


    @Override
    public Boolean updateMallGoodsOrderState(String orderNo, String transResult, String rootHomeUrl) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (transResult.equals("1") && tradeOffline != null
                && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            // 查询是否商品订单信息
            OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForPay.getType());
            Long shopid = null;
            if (orderGood.getShopId() != null && orderGood.getShopId() != 0) {
                shopid = orderGood.getShopId();
            }
            if (orderGood == null) {
                throw new ApplicationException(Rescode.FAIL, "商品订单信息不存在");
            }
            orderGood.setPayTime(new Date());
            orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());


            //优惠券金额大于订单金的时候

            if(orderGood.getCouponCover() !=null && orderGood.getCouponCover()>orderGood.getGoodAmount()){
                orderGood.setCouponCover(orderGood.getGoodAmount());
            }
            if(tradeOffline.getDiscountAmount()!=null && tradeOffline.getDiscountAmount()>tradeOffline.getOrderAmount()){
                tradeOffline.setDiscountAmount(tradeOffline.getOrderAmount());
            }

            orderGoodMapper.updateByPrimaryKey(orderGood);
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            //核销积分优惠券
            if (orderGood.getBonusAmount() > 0) {
                bonusVerifyLogMapper.confirmBonusVerify(orderGood.getId());

                /**
                 * 更新订单号与
                 */
                BonusVerifyLog bonusVerifyLog = bonusVerifyLogMapper.queryBonusVerifyLog(orderGood.getId());
                bonusVerifyLog.setOrderId(tradeOffline.getId());
//                bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);
                //更新门店积分余额
//                if (shopid != null) {
//                    bonusVerifyShopMapper.updateShopBonusData(bonusVerifyLog.getAdjustAmount(), bonusVerifyLog.getShopId());
//                }

               //积分结算到门店开始
                if(shopid !=null && shopid !=0){

                    //结算积分给门店 start
                    Integer bonusamount = tradeOffline.getBonusAmount();
                    Long groupId = tradeOffline.getGroupId();
                    if(bonusamount != 0) {
                        float settlerate = 0;
                        //根据shopid获取积分结算规则
                        BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopid);
                        if (bonusVerifyRule != null) {//如果有门店自定义的
                            settlerate = bonusVerifyRule.getSettleRate();
                        } else {//如果商圈给门店设置的
                            bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(shopid, groupId);
                            if (bonusVerifyRule != null) {
                                settlerate = bonusVerifyRule.getSettleRate();
                            } else {
                                bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
                                if (bonusVerifyRule != null) {
                                    settlerate = bonusVerifyRule.getSettleRate();
                                }
                            }
                        }

                        //计算积分
                        if (settlerate != 0) {
                            int bonus = (int) (bonusamount * settlerate / 100);

                            logger.info("+++++++结算到门店的积分+++++++"+bonus);
                            //积分结算给门店
                            BonusVerifyShop result = bonusVerifyShopMapper.bonusShopVerify(groupId,shopid);
                            if(result !=null){
                                bonusVerifyShopMapper.updateShopVerifyBonus(groupId, shopid, bonus);
                            }else{
                                BonusVerifyShop bonusVerifyShop = new BonusVerifyShop();
                                bonusVerifyShop.setGmtCreate(new Date());
                                bonusVerifyShop.setGmtModified(new Date());
                                bonusVerifyShop.setGroupId(groupId);
                                bonusVerifyShop.setShopId(shopid);
                                bonusVerifyShop.setAmount(bonus);
                                bonusVerifyShop.setThisAmount(bonus);
                                bonusVerifyShop.setVerifiedAmount(bonus);
                                bonusVerifyShop.setStatus(1);
                                bonusVerifyShopMapper.insertSelective(bonusVerifyShop);
                            }

                            //添加积分结算记录
                            bonusVerifyLog.setSettingAmount(bonus);
                            bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);

                        }
                    }
                    //结算积分给门店 end

                }else{
                    bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);
                }



                memberMapper.updateActualConsumeBonus(orderGood.getMemberId(), orderGood.getBonusAmount());
            }
            if (orderGood.getCouponCover() > 0) {
                couponUserMapper.updateVerifyUserCouponByOrderId2(orderGood.getId());
            }

            //结算和分润 start
/*			Long shopid = orderGood.getShopId();
            Group group = groupMapper.selectByPrimaryKey(orderGood.getGroupId());

			int profileamount = 0;
			//对供货价求和
			Long ordergoodid = orderGood.getId();
			int supplyprice = 0;

			List<OrderGoodItem> list = orderGoodItemMapper.listByOrderId(ordergoodid);
			for(int k = 0;k<list.size(); k++) {
				OrderGoodItem ogi = list.get(k);
				Long gsi = ogi.getGoodSpecId();
				Long goodid = ogi.getGoodId();
				if(gsi != null) {//有规格，查询该规格对应的供货价
					MallEntityGoodSpec megs = mallEntityGoodSpecMapper.selectByPrimaryKey(gsi);
					Integer supply_price = megs.getPrice3() * ogi.getGoodNum();
					supplyprice += supply_price;
				} else {//无规格，查询该商品对应的供货价
					MallEntityGood meg = mallEntityGoodMapper.selectByPrimaryKey(goodid);
					Integer supply_price = meg.getSupplyPrice() * ogi.getGoodNum();
					supplyprice += supply_price;
				}
			}

			//运费
			int freightcharge = orderGood.getFreightCharge();

			//计算交易手续费
			int ordertradefee = (int)((supplyprice + freightcharge) * Double.parseDouble(tradefee));

			//根据订单的供货价+运费-交易手续费进行计算结算金额
			int settleamount = supplyprice + freightcharge - ordertradefee;
			//如果是商户的商品则直接结算给商户
			if(shopid != null) {
				Shop shop = shopMapper.selectByPrimaryKey(shopid);
				//给商户增加冻结金额
				walletService.updateLockedAmount(shop.getId()+"", "3", "+"+settleamount, "1", group.getFreezeTime(),tradeOffline.getOrderId());
			}

			//计算分润金额
			profileamount = tradeOffline.getRealAmount() - settleamount;

			if(profileamount >= 0) {
				Map param = new HashMap();
				param.put("groupid", group.getId()+"");
				param.put("profileamount", profileamount+"");
				param.put("orderno", tradeOffline.getOrderId());
				//调用分润接口
				HttpClientUtil.post(profiturl + "group/profile/computeEntityProfile", param);
			}
			//计算分润
*/
            try {
                //profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
                memberService.insertMemberTradeDataAsyn(orderGood.getMemberId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
            } catch (Exception e) {
                e.printStackTrace();
                throw new ApplicationException(Rescode.FAIL, "分润交易异常");
            }
            try {
                templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template4.getType(), tradeOffline.getPayerId(),
                        tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
            } catch (Exception e) {
                logger.info("模板消息发送失败" + e);
            }

            Member member = memberMapper.selectByPrimaryKey(orderGood.getMemberId());

            Long finalShopid = shopid;
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    wxApiMallService.newBenefitCalc(finalShopid, tradeOffline.getRealAmount(), member.getGroupId(), member, tradeOffline.getId());
                }
            });
            return true;
        } else {

            // 查询是否商品订单信息
            OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForPay.getType());
            if (orderGood != null) {
                orderGood.setStatus(BizEnum.MallOrderStatus.closed.getType());
                orderGoodMapper.updateByPrimaryKey(orderGood);
            }

            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
            tradeOffline.setMemo("支付失败");
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            return false;
        }

    }


    @Override
    public Boolean updateServiceGoodsOrderState(String orderNo, String transResult, String rootHomeUrl) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (transResult.equals("1") && tradeOffline != null
                && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            Date date = new Date();
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            // 查询是否商品订单信息
            String orderId = tradeOffline.getOrderId();
            OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectOrderServiceGoodInfo(orderId, BizEnum.ServiceOrderStatus.WaitingForPay.getType());
            if (orderServiceGood == null) {
                throw new ApplicationException(Rescode.FAIL, "服务商品订单信息不存在");
            }


            MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());
            if (mallGood == null) {
                throw new ApplicationException(Rescode.FAIL, "商品信息不存在");
            }
            //生成商品订单及劵码 已更新服务订单
            GenerateCouponCode(mallGood, tradeOffline, orderServiceGood, date);

            //优惠金额大于订单金额
            if(tradeOffline.getDiscountAmount() !=null &&tradeOffline.getDiscountAmount()>tradeOffline.getOrderAmount()){
                tradeOffline.setDiscountAmount(tradeOffline.getOrderAmount());
            }

            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            //核销积分优惠券
            if (tradeOffline.getBonusValue() != null && tradeOffline.getBonusValue() > 0) {
                bonusVerifyLogMapper.confirmBonusVerify(tradeOffline.getId());
                memberMapper.updateActualConsumeBonus(tradeOffline.getMemberId(), tradeOffline.getBonusAmount());
            }
            if (tradeOffline.getDiscountAmount() != null && tradeOffline.getDiscountAmount() > 0) {
                couponUserMapper.updateVerifyUserCouponByOrderId2(tradeOffline.getId());
            }

            try {
                profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
                logger.info("插入会员交易数据带积分异步开始--------------------------------");
                memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
                logger.info("插入会员交易数据带积分异步结束--------------------------------");
            } catch (Exception e) {
                e.printStackTrace();
                throw new ApplicationException(Rescode.FAIL, "分润交易异常");
            }

            try {
                templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template4.getType(), tradeOffline.getPayerId(),
                        tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
            } catch (Exception e) {
                logger.info("模板消息发送失败" + e);
            }
            return true;
        } else {

            OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectOrderServiceGoodInfo(tradeOffline.getOrderId(), BizEnum.ServiceOrderStatus.WaitingForPay.getType());
            if (orderServiceGood == null) {
                throw new ApplicationException(Rescode.FAIL, "服务商品订单信息不存在");
            }
            orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.Closed.getType());
            orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);

            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
            tradeOffline.setMemo("支付失败");
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return false;

        }

    }

    @Override
    public TradeOffline updatewalletOrderState(String orderNo, String respCode) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (tradeOffline != null) {
            if (respCode.equals("0000")) {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
                return tradeOffline;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    /**
     * 只做回调推送 不处理实际业务逻辑
     */
    @Override
    public Boolean updateOrderQueryNotify() throws ApplicationException {
        List<Group> groupList = groupMapper.selectAll();
        for (Group group : groupList) {
            List<TradeOffline> tradeOfflineList = tradeOfflineMapper.selectWaitingForPay(group.getId());
            for (TradeOffline tradeOfflineBeen : tradeOfflineList) {
                PayResult payResult = IPayAPI.orderQueryNotify(tradeOfflineBeen.getPayOrderid(), group.getPayGroupCode(),
                        tradeOfflineBeen.getTransactionType().equals((byte) BizEnum.TransactionType.Withdraw.getType()) ? "0" : "1");
                if (payResult.getRespCode().equals("0000")) {
                    logger.info("成功");
                } else {
                    logger.info("失败");
                }
            }
        }
        return true;
    }


    @Override
    public Boolean updateOfflineAliPay(HashMap<String, String> params, String orderNo, Boolean flag) throws ApplicationException {
        // 交易成功 即使再次回调也不做处理
        Boolean fls = addBalance(orderNo, flag);
        return fls;

    }

    @Override
    public Boolean updateGoodsOfflineAliPay(HashMap<String, String> params, String orderNo, Boolean flag) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            // 查询是否商品订单信息
            OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForPay.getType());
            if (orderGood == null) {
                throw new ApplicationException(Rescode.FAIL, "商品订单信息不存在");
            }
            orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());
            orderGoodMapper.updateByPrimaryKey(orderGood);
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return true;
        } else {
            return false;
        }

    }

    @Override
    public WxPayOrderNotifyResult WxPayResult(HttpServletRequest request) throws ApplicationException {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            // 解析返回参数
            WxPayOrderNotifyResult wxPayOrderNotifyResult = WxPayOrderNotifyResult.fromXML(xmlResult);
            // 蛋疼的回调不能带参数，只能获取Appid然后查询数据库参数配置再做签名验证
            GroupPayconfig groupPayconfig = groupPayconfigMapper.selectAppId(wxPayOrderNotifyResult.getAppid());
            if (groupPayconfig == null) {
                logger.info("=================================商户参数未配置===================================");
                throw new ApplicationException(Rescode.FAIL, "商户参数未配置");
            }
            WxPayConfig wxPayConfig = new WxPayConfig();
            WxPayService wxPayService = new WxPayServiceImpl();
            wxPayConfig.setAppId(groupPayconfig.getWxAppid());
            wxPayConfig.setMchId(groupPayconfig.getWxMerchantno());
            wxPayConfig.setMchKey(groupPayconfig.getWxPayKey());
            wxPayService.setConfig(wxPayConfig);
            WxPayOrderNotifyResult result = wxPayService.getOrderNotifyResult(xmlResult);
            return result;
        } catch (Exception e) {
            logger.info("微信回调结果异常,异常原因" + e.getMessage());
            return null;
        }
    }

    public Boolean addBalance(String orderId, Boolean flag) {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderId);
        // 交易成功 即使再次回调也不做处理
        if (tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            if (flag == false) {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
                tradeOfflineMapper.updateByOrderIdSelective(tradeOffline);
                logger.info("订单已关闭");
                return true;
            }
            Member member = memberMapper.queryGroup(tradeOffline.getPayerId());
            if (orderId.startsWith(Const.APP_RECHARGE)) {
                // 增加余额记录 需要添加一条记录信息
                String orgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmss");
                Date date = new Date();
                TradeOffline trade = new TradeOffline();
                trade.setGmtCreate(date);
                trade.setGmtModified(date);
                trade.setGroupId(member.getGroupId());
                trade.setOrderId(orgOrderNum);
                trade.setPayerId(tradeOffline.getPayerId());// 付款者id号
                trade.setPayerName(member.getName());// 付款者姓名
                trade.setPayerType((byte) CommonEnum.UserType.User.getType());
                trade.setPayType((byte) BizEnum.PaymentType.Wallet.getType());// 支付方式
                // 生成订单支付方式未知
                trade.setReceiverId(null);// 接收者id
                trade.setReceiverName(null);// 接收者 此处以核销录入数据
                trade.setTransactionType((byte) BizEnum.TransactionType.AddBalance.getType());// 交易类型
                trade.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
                trade.setOrderAmount(Integer.valueOf(tradeOffline.getOrderAmount())); // 订单金额
                trade.setDiscountAmount(0);// 折扣金额
                trade.setRealAmount(Integer.valueOf(tradeOffline.getOrderAmount()));// 实付金额
                trade.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
                trade.setIsWallet(false);
                trade.setGoodType(null);// 商品类型(线上用) ？
                trade.setMemo("用户充值余额增加");
                trade.setDetail("用户充值余额增加");
                trade.setMerchantNo(null);// 商户号(对账用)
                trade.setTerminalNo(null);// 商户终端号
                trade.setPayAccount("");// 支付卡号
                trade.setScanOrganization(null);// 扫码付入网机构
                trade.setCrcodeStr(null);
                trade.setOldOrderId(null);
                trade.setDividableAmount(0);// 可分润金额
                trade.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
                trade.setPayOrderid(orgOrderNum);
                trade.setPayBakOrderid(null);
                trade.setInNetCompany(null);// 入网机构
                tradeOfflineMapper.insertSelective(trade);
                try {
                    walletService.updateUserLockedAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId(), tradeOffline.getOrderAmount() + "", "1", 0, orgOrderNum);
                    // 增加余额成功
                    tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                    tradeOfflineMapper.updateByOrderIdSelective(tradeOffline);
                    logger.info("--余额增加成功--");
                } catch (ApplicationException e) {
                    e.printStackTrace();
                }
            } else if (orderId.startsWith(Const.APP_CONSUME)) {
                tradeOfflineMapper.updateByOrderIdSelective(tradeOffline);
                logger.info("---消费回调更新成功---");
            }

        } else {
            logger.info("未找到该笔订单");
        }
        return false;
    }

    @Override
    public Boolean updateWithDrawNotify(String orderNo, String transResult) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (tradeOffline == null) {
            logger.info("=========================未查询到该笔订单========================================");
            return false;
        }
        // 交易成功 即使再次回调也不做处理
        if (tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {

            if ("INVALID".equals(transResult)) {

            } else if ("TX_SUCCESS".equals(transResult)) {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOffline.setMemo("打款成功");
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                walletService.updateBankWithdrawalNotify(orderNo, tradeOffline.getPayerId(), true, 1);
                return true;
            } else {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
                tradeOffline.setMemo(transResult);
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                walletService.updateBankWithdrawalNotify(orderNo, tradeOffline.getPayerId(), false, 1);
            }

        }
        return false;
    }

    @Override
    public Boolean updateWxWithDrawNotify(String orderNo, String transResult, String homeRootUrl) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (tradeOffline == null) {
            logger.info("=========================未查询到该笔订单========================================");
            return null;
        }
        // 交易成功 即使再次回调也不做处理
        if (tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            if ("INVALID".equals(transResult)) {

            } else if ("TX_SUCCESS".equals(transResult)) {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOffline.setMemo("打款成功");
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                walletService.updateBankWithdrawalNotify(orderNo, tradeOffline.getPayerId(), true, 1);
                if (homeRootUrl != null) {
                    try {
                        templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template3.getType(), tradeOffline.getPayerId(),
                                tradeOffline.getGroupId(), null, homeRootUrl);
                    } catch (Exception e) {
                        logger.info("模板消息发送失败" + e);
                    }
                }
                return true;
            } else {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
                tradeOffline.setMemo(transResult);
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                walletService.updateBankWithdrawalNotify(orderNo, tradeOffline.getPayerId(), false, 1);
                return false;
            }


        }
        return false;
    }


    @Override
    public Boolean updateSySWithDrawNotify(String orderNo, String transResult) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderNo);
        if (tradeOffline == null) {
            logger.info("=========================未查询到该笔订单========================================");
            return false;
        }
        TradeWithdraw tradeWithdraw = tradeWithdrawMapper.selectByOrderNum(orderNo);
        if (tradeWithdraw == null) {
            return false;
        }

        //判断系统系统是代理商还是门店
        Integer type = null;
        if (tradeOffline.getPayerType().equals((byte) CommonEnum.UserType.Agents.getType())) {
            type = 2;
        } else if (tradeOffline.getPayerType().equals((byte) CommonEnum.UserType.Store.getType())) {
            type = 3;
        }

        // 交易成功 即使再次回调也不做处理
        if (tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            if ("INVALID".equals(transResult)) {

            } else if ("TX_SUCCESS".equals(transResult)) {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOffline.setMemo("打款成功");
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                tradeWithdraw.setStatus(BizEnum.WithdrawStatus.SettleSuccess.getType());
                tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);

                walletService.updateBankWithdrawalNotify(orderNo, tradeOffline.getPayerId(), true, type);
                return true;
            } else {
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
                tradeOffline.setMemo(transResult);
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                tradeWithdraw.setStatus(BizEnum.WithdrawStatus.SettleFail.getType());
                tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);

                walletService.updateBankWithdrawalNotify(orderNo, tradeOffline.getPayerId(), false, type);
                return false;
            }
        }
        return false;
    }


    @Override
    public Boolean updateOfflineWxPay(WxPayOrderNotifyResult result) throws ApplicationException {
        String orderId = result.getOutTradeNo();
        String tradeNo = result.getTransactionId();
        logger.info("=================================orderId===================================" + orderId);
        logger.info("=================================tradeNo===================================" + tradeNo);
        if (result.getResultCode().equals("SUCCESS")) {
            Boolean flag = addBalance(orderId, true);
            return flag;
        } else if (result.getResultCode().equals("FAIL")) {
            addBalance(orderId, false);
            return false;
        }
        return false;
    }

    @Override
    public Boolean updateGoodsOfflineWxPay(WxPayOrderNotifyResult result) throws ApplicationException {
        String orderId = result.getOutTradeNo();
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orderId);
        if (tradeOffline != null && !tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForPay.getType());
            if (orderGood == null) {
                throw new ApplicationException(Rescode.FAIL, "商品订单信息不存在");
            }
            orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());
            orderGoodMapper.updateByPrimaryKey(orderGood);
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Boolean updatefinishSendMessage(String outTradeNo, String messageType) throws Exception {
        logger.info("=================================消息推送===================================" + outTradeNo);
        TradeOffline tradeOffline = tradeOfflineMapper.selectOutTradeNo(outTradeNo, (byte) BizEnum.TransactionStatus.Success.getType());
        if (tradeOffline == null) {
            return false;
        }
        if (messageType.equals(UserAuthApi.MC_BLANCE_CHANGE)) { // 余额变动通知
            logger.info("=================================余额变动通知===================================" + outTradeNo);
            Member member = memberMapper.queryGroup(tradeOffline.getPayerId());
            String banance = queryAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId());
            SysMessageBase sysMessageBase = new SysMessageBase();
            sysMessageBase.setGroupShopJionId(null);
            sysMessageBase.setPosRepairId(null);
            sysMessageBase.setMessageType((byte) BizEnum.MessageType.AmountChange.getType());
            sysMessageBase.setSendFrom(member.getGroupId());
            sysMessageBase.setSendUserId(member.getUserId());
            sysMessageBase.setTitle("余额变动通知");
            sysMessageBase.setLevel((byte) 0);
            sysMessageBase.setRemark("余额变动通知");
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"钱包进行充值,", member.getName(), member.getCardNo());
            String message2 = "变化金额" + String.format("%.2f", Double.valueOf(tradeOffline.getOrderAmount()) / 100);
            String message3 = String.format(",您钱包帐户余额为%.2f元", Double.valueOf(banance) / 100);
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message3);
            sysMessageBase.setGmtCreate(new Date());
            sysMessageBase.setGmtModified(new Date());
            sysMessageBaseMapper.insert(sysMessageBase);
            SysMessageInfo sysMessageInfo = new SysMessageInfo();
            sysMessageInfo.setGmtCreate(new Date());
            sysMessageInfo.setGmtModified(new Date());
            sysMessageInfo.setReceviceUserId(member.getUserId());
            sysMessageInfo.setHasRead((byte) 0);
            sysMessageInfo.setMessageId(sysMessageBase.getId());
            sysMessageInfo.setIsDelete(null);
            sysMessageInfoMapper.insert(sysMessageInfo);
            // 进行推送 ：：账户余额变动 ,模板：您的账户余额变动金额{0}，余额{1}
            List<String> paramList = new ArrayList<String>();
            // paramList.add(member.getMemberCustomerName());
            paramList.add(String.format("%.2f", Double.valueOf(tradeOffline.getOrderAmount()) / 100));

            logger.info("=================================余额===================================" + banance);
            paramList.add(String.format("%.2f", Double.valueOf(banance) / 100));
            boolean sendResult = UserAuthApi.finishSendMessage(sysMessageInfo.getId(), member.getThirdUserId(), UserAuthApi.MC_BLANCE_CHANGE, paramList);
            if (sendResult) {
                logger.info("=================================消息推送成功===================================");
            }
            return sendResult;
        } else if (messageType.equals(UserAuthApi.MC_TRANSFER)) { // 钱包转账通知
            Member member = memberMapper.queryGroup(Long.valueOf(tradeOffline.getReceiverId()));
            Member memberPay = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
            // 进行推送钱包转账通知 ,模板：已经收到{0}转账,金额为{1},余额为{2}
            List<String> paramList = new ArrayList<String>();
            paramList.add(memberPay.getName() + "一笔");
            String paramList1 = String.format("%.2f", Double.valueOf(tradeOffline.getOrderAmount()) / 100);
            paramList.add(paramList1);
            String banance = queryAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId());
            String paramList2 = String.format("%.2f", Double.valueOf(banance) / 100);
            paramList.add(paramList2);
            String memo = String.format("尊敬的：%s \r\n已收到\"%s\"一笔转账，金额为%s,当前余额:%s", member.getName(), memberPay.getName(), paramList1, paramList2);
            SysMessageBase sysMessageBase = new SysMessageBase();
            sysMessageBase.setGroupShopJionId(null);
            sysMessageBase.setPosRepairId(null);
            sysMessageBase.setMessageType((byte) BizEnum.MessageType.AmountChange.getType());
            sysMessageBase.setSendFrom(member.getGroupId());
            sysMessageBase.setSendUserId(member.getUserId());
            sysMessageBase.setTitle("钱包转账通知 ");
            sysMessageBase.setLevel((byte) 0);
            sysMessageBase.setRemark("钱包转账通知 ");
            sysMessageBase.setMemo(memo);
            sysMessageBase.setGmtCreate(new Date());
            sysMessageBase.setGmtModified(new Date());
            sysMessageBaseMapper.insert(sysMessageBase);
            SysMessageInfo sysMessageInfo = new SysMessageInfo();
            sysMessageInfo.setGmtCreate(new Date());
            sysMessageInfo.setGmtModified(new Date());
            sysMessageInfo.setReceviceUserId(member.getUserId());
            sysMessageInfo.setHasRead((byte) 0);
            sysMessageInfo.setMessageId(sysMessageBase.getId());
            sysMessageInfo.setIsDelete(null);
            sysMessageInfoMapper.insert(sysMessageInfo);
            boolean sendResult = UserAuthApi.finishSendMessage(sysMessageInfo.getId(), member.getThirdUserId(), UserAuthApi.MC_TRANSFER, paramList);
            if (sendResult) {
                logger.info("=================================消息推送成功===================================");
            }
            return sendResult;
        } else if (messageType.equals(UserAuthApi.MC_WITHDRAW)) { // 钱包提现通知
            logger.info("=================================钱包提现通知====================================" + outTradeNo);
            Member member = memberMapper.queryGroup(tradeOffline.getPayerId());
            String banance = queryAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId());
            SysMessageBase sysMessageBase = new SysMessageBase();
            sysMessageBase.setGroupShopJionId(null);
            sysMessageBase.setPosRepairId(null);
            sysMessageBase.setMessageType((byte) BizEnum.MessageType.AmountChange.getType());
            sysMessageBase.setSendFrom(member.getGroupId());
            sysMessageBase.setSendUserId(member.getUserId());
            sysMessageBase.setTitle("提现结果通知");
            sysMessageBase.setLevel((byte) 0);
            sysMessageBase.setRemark("提现结果通知");
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"进行了提现操作", member.getName(), member.getCardNo() + ",");
            String message2 = "提现金额为" + tradeOffline.getOrderAmount().doubleValue() / 100;
            String message3 = "提现银行账户信息为：" + StringReplaceUtil.bankCardReplaceWithStar(4, tradeOffline.getPayAccount()) + ",交易订单号为" + outTradeNo;
            String message4 = String.format(",您钱包帐户余额为%.2f元", Double.valueOf(banance) / 100);
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message3 + "\r\n" + message4);
            sysMessageBase.setGmtCreate(new Date());
            sysMessageBase.setGmtModified(new Date());
            sysMessageBaseMapper.insert(sysMessageBase);
            SysMessageInfo sysMessageInfo = new SysMessageInfo();
            sysMessageInfo.setGmtCreate(new Date());
            sysMessageInfo.setGmtModified(new Date());
            sysMessageInfo.setReceviceUserId(member.getUserId());
            sysMessageInfo.setHasRead((byte) 0);
            sysMessageInfo.setMessageId(sysMessageBase.getId());
            sysMessageInfo.setIsDelete(null);
            sysMessageInfoMapper.insert(sysMessageInfo);
            // 进行推送 提现 ,模板：提现{0},提现金额为{1}，余额为{2}
            List<String> paramList = new ArrayList<String>();
            paramList.add("成功");
            paramList.add(String.format("%.2f", Double.valueOf(tradeOffline.getOrderAmount()) / 100));
            logger.info("=================================余额===================================" + banance);
            paramList.add(String.format("%.2f", Double.valueOf(banance) / 100));
            boolean sendResult = UserAuthApi.finishSendMessage(sysMessageInfo.getId(), member.getThirdUserId(), UserAuthApi.MC_WITHDRAW, paramList);
            if (sendResult) {
                logger.info("=================================消息推送成功===================================");
            }
            return sendResult;
        } else if (messageType.equals(UserAuthApi.MC_CREDTCARD_WITHDRAW)) { // 钱包信用卡还款通知
            logger.info("=================================钱包钱包信用卡还款通知====================================" + outTradeNo);
            Member member = memberMapper.queryGroup(tradeOffline.getPayerId());
            String banance = queryAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId());
            SysMessageBase sysMessageBase = new SysMessageBase();
            sysMessageBase.setGroupShopJionId(null);
            sysMessageBase.setPosRepairId(null);
            sysMessageBase.setMessageType((byte) BizEnum.MessageType.AmountChange.getType());
            sysMessageBase.setSendFrom(member.getGroupId());
            sysMessageBase.setSendUserId(member.getUserId());
            sysMessageBase.setTitle("信用卡还款通知");
            sysMessageBase.setLevel((byte) 0);
            sysMessageBase.setRemark("信用卡还款通知");
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"进行了信用卡还款操作", member.getName(), member.getCardNo());
            String message2 = "还款金额为" + tradeOffline.getOrderAmount().doubleValue() / 100 + ",";
            String message3 = "还款银行账户信息为：" + StringReplaceUtil.bankCardReplaceWithStar(4, tradeOffline.getPayAccount()) + ",交易订单号为" + outTradeNo + ",";
            String message4 = String.format("您钱包帐户余额为%.2f元", Double.valueOf(banance) / 100);
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message3 + "\r\n" + message4);
            sysMessageBase.setGmtCreate(new Date());
            sysMessageBase.setGmtModified(new Date());
            sysMessageBaseMapper.insert(sysMessageBase);
            SysMessageInfo sysMessageInfo = new SysMessageInfo();
            sysMessageInfo.setGmtCreate(new Date());
            sysMessageInfo.setGmtModified(new Date());
            sysMessageInfo.setReceviceUserId(member.getUserId());
            sysMessageInfo.setHasRead((byte) 0);
            sysMessageInfo.setMessageId(sysMessageBase.getId());
            sysMessageInfo.setIsDelete(null);
            sysMessageInfoMapper.insert(sysMessageInfo);
            // 模板：信用卡还款{0},还款金额为{1}，余额为{2} -
            List<String> paramList = new ArrayList<String>();
            paramList.add("成功");
            paramList.add(String.format("%.2f", Double.valueOf(tradeOffline.getOrderAmount()) / 100));
            logger.info("=================================余额===================================" + banance);
            paramList.add(String.format("%.2f", Double.valueOf(banance) / 100));
            boolean sendResult = UserAuthApi.finishSendMessage(sysMessageInfo.getId(), member.getThirdUserId(), UserAuthApi.MC_CREDTCARD_WITHDRAW, paramList);
            if (sendResult) {
                logger.info("=================================消息推送成功===================================");
            }
            return sendResult;
        }

        return false;
    }

    @Override
    public Boolean finishSendYKSuccessMessage(YsOilcardOrder oilcardOrder) throws Exception {
        logger.info("=================================油卡充值通知 ====================================" + oilcardOrder.getId());

        Member member = memberMapper.selectYlUserId(oilcardOrder.getMemberId());
        String oilCardType = oilcardOrder.getOilcardType();
        String oilCardNum = oilcardOrder.getOilcardNumber();
        Integer amount = oilcardOrder.getRechargeAmount();
        SysMessageBase sysMessageBase = new SysMessageBase();
        sysMessageBase.setGroupShopJionId(null);
        sysMessageBase.setPosRepairId(null);
        sysMessageBase.setMessageType((byte) BizEnum.MessageType.AmountChange.getType());
        sysMessageBase.setSendFrom(member.getGroupId());
        sysMessageBase.setSendUserId(member.getUserId());
        sysMessageBase.setTitle("油卡充值成功通知");
        sysMessageBase.setLevel((byte) 0);
        sysMessageBase.setRemark("油卡充值成功通知");
        String message1 = "油卡充值：" + (oilcardOrder.getOrderPackageType().intValue() == 0 ? "及时充值" : "预充值") + "\r\n油卡类型："
                + (oilCardType.equalsIgnoreCase("ZSH") ? "中石化" : "中石油");
        String message2 = "油卡卡号：" + oilCardNum + "\r\n充值金额：" + String.format("%.2f", amount / 100.0) + "元\r\n充值时间："
                + DateUtil.fomatDate(oilcardOrder.getPaymentTime(), DateUtil.sdfTimeMM);
        String message3 = "系统正在为您充值，由于供应商在确系统原因，预计将在15~30分钟延迟。在油卡使用前，请务必到油站服务区进行【圈存】。";
        sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message3);
        sysMessageBase.setGmtCreate(new Date());
        sysMessageBase.setGmtModified(new Date());
        sysMessageBaseMapper.insert(sysMessageBase);
        SysMessageInfo sysMessageInfo = new SysMessageInfo();
        sysMessageInfo.setGmtCreate(new Date());
        sysMessageInfo.setGmtModified(new Date());
        sysMessageInfo.setReceviceUserId(member.getUserId());
        sysMessageInfo.setHasRead((byte) 0);
        sysMessageInfo.setMessageId(sysMessageBase.getId());
        sysMessageInfo.setIsDelete(null);
        sysMessageInfoMapper.insert(sysMessageInfo);
        // 模板：您的{0}油卡成功充值金额{1}元
        List<String> paramList = new ArrayList<String>();
        String content = null;
        if (oilCardType.equalsIgnoreCase("ZSH")) {
            content = "(尾号为" + oilCardNum.substring(oilCardNum.length() - 4) + "的中石化)";
        } else {
            content = "(尾号为" + oilCardNum.substring(oilCardNum.length() - 4) + "的中石油)";
        }
        paramList.add(content);
        paramList.add(String.format("%.2f", amount / 100.0));
        boolean sendResult = UserAuthApi.finishSendMessage(sysMessageInfo.getId(), member.getThirdUserId(), UserAuthApi.MC_OILCHARGE_NOTIFY, paramList);
        if (sendResult) {
            logger.info("=================================消息推送成功===================================");
        }
        return sendResult;
    }

    /**
     * 消费购买通知
     *
     * @param tradeOrderId    交易记录Id
     * @param consumptionType 消费说明
     * @return
     * @throws Exception
     */
    public Boolean finishBuySendMessage(Long tradeOrderId, String consumptionType) throws Exception {

        TradeOffline tradeOffline = tradeOfflineMapper.selectByPrimaryKey(tradeOrderId);
        if (tradeOffline == null || tradeOffline.getTransactionStatus().intValue() == BizEnum.TransactionStatus.Success.getType()) {
            return false;
        }
        return finishBuySendMessage(tradeOffline, consumptionType);
    }

    @Override
    public Boolean finishBuySendMessage(String outTradeNo, String consumptionType) throws Exception {
        logger.info("=================================消息推送===================================" + outTradeNo);
        TradeOffline tradeOffline = tradeOfflineMapper.selectOutTradeNo(outTradeNo, (byte) BizEnum.TransactionStatus.Success.getType());
        if (tradeOffline == null) {
            return false;
        }
        return finishBuySendMessage(tradeOffline, consumptionType);

    }

    /**
     * 完成用户消费通知
     *
     * @param tradeOffline
     * @param consumptionType
     * @return
     * @throws Exception
     */
    private Boolean finishBuySendMessage(TradeOffline tradeOffline, String consumptionType) throws Exception {
        Member member = memberMapper.queryGroup(tradeOffline.getPayerId());
        String banance = queryAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId());
        SysMessageBase sysMessageBase = new SysMessageBase();
        sysMessageBase.setGroupShopJionId(null);
        sysMessageBase.setPosRepairId(null);
        sysMessageBase.setMessageType((byte) BizEnum.MessageType.AmountChange.getType());
        sysMessageBase.setSendFrom(member.getGroupId());
        sysMessageBase.setSendUserId(member.getUserId());
        sysMessageBase.setTitle(consumptionType + "通知");
        sysMessageBase.setLevel((byte) 0);
        sysMessageBase.setRemark(consumptionType + "通知");
        byte payType = tradeOffline.getPayType();
        if (BizEnum.PaymentType.Wallet.getType() == payType) {
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"钱包进行" + consumptionType + "，", member.getName(), member.getCardNo());
            String message2 = "消费金额" + String.format("%.2f", Double.valueOf(tradeOffline.getRealAmount()) / 100);
            String message3 = String.format(",您钱包帐户余额为%.2f元", Double.valueOf(banance) / 100);
            String message4 = "交易订单号：" + tradeOffline.getPayOrderid();
            String message5 = "交易时间：" + SysUtils.formatDate(tradeOffline.getGmtCreate(), "yyyy-MM-dd HH:mm:ss");
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message3 + "\r\n" + message4 + "\r\n" + message5);
        } else if (BizEnum.PaymentType.AliPay.getType() == payType) {
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"支付宝进行" + consumptionType + ",", member.getName(), member.getCardNo());
            String message2 = "消费金额" + String.format("%.2f", Double.valueOf(tradeOffline.getRealAmount()) / 100);
            String message4 = "交易订单号：" + tradeOffline.getPayOrderid();
            String message5 = "交易时间：" + SysUtils.formatDate(tradeOffline.getGmtCreate(), "yyyy-MM-dd HH:mm:ss");
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message4 + "\r\n" + message5);
        } else if (BizEnum.PaymentType.WebChat.getType() == payType) {
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"微信进行" + consumptionType + ",", member.getName(), member.getCardNo());
            String message2 = "消费金额" + String.format("%.2f", Double.valueOf(tradeOffline.getRealAmount()) / 100);
            String message4 = "交易订单号：" + tradeOffline.getPayOrderid();
            String message5 = "交易时间：" + SysUtils.formatDate(tradeOffline.getGmtCreate(), "yyyy-MM-dd HH:mm:ss");
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message4 + "\r\n" + message5);
        } else if (BizEnum.PaymentType.NetBankCardQuick.getType() == payType) {
            String message1 = String.format("尊敬的：%s \r\n您的帐号\"%s\"银行卡进" + consumptionType + ",", member.getName(), member.getCardNo());
            String message2 = "消费金额" + String.format("%.2f", Double.valueOf(tradeOffline.getRealAmount()) / 100);
            String message4 = "交易订单号：" + tradeOffline.getPayOrderid();
            String message5 = "交易时间：" + SysUtils.formatDate(tradeOffline.getGmtCreate(), "yyyy-MM-dd HH:mm:ss");
            sysMessageBase.setMemo(message1 + "\r\n" + message2 + "\r\n" + message4 + "\r\n" + message5);
        }
        sysMessageBase.setGmtCreate(new Date());
        sysMessageBase.setGmtModified(new Date());
        sysMessageBaseMapper.insert(sysMessageBase);
        SysMessageInfo sysMessageInfo = new SysMessageInfo();
        sysMessageInfo.setGmtCreate(new Date());
        sysMessageInfo.setGmtModified(new Date());
        sysMessageInfo.setReceviceUserId(member.getUserId());
        sysMessageInfo.setHasRead((byte) 0);
        sysMessageInfo.setMessageId(sysMessageBase.getId());
        sysMessageInfo.setIsDelete(null);
        sysMessageInfoMapper.insert(sysMessageInfo);
        // 进行推送 ：：
        List<String> paramList = new ArrayList<String>();
        // paramList.add(member.getMemberCustomerName());
        logger.info("=================================开始消费通知===================================");
        paramList.add(consumptionType);
        paramList.add(String.format("%.2f", Double.valueOf(tradeOffline.getRealAmount()) / 100));
        boolean sendResult = UserAuthApi.finishSendMessage(sysMessageInfo.getId(), member.getThirdUserId(), UserAuthApi.MC_SALE_PAY, paramList);
        if (sendResult) {
            logger.info("=================================消息推送成功===================================");
        }
        return sendResult;
    }

    /**
     * 查询用户余额
     *
     * @param userId
     * @param
     * @return
     * @throws Exception
     */
    private String queryAmount(String virtualCard, String payGroupCode, Long userId) throws Exception {
        Wallet wallet = walletService.selectwallet(virtualCard, payGroupCode, userId);
        Integer sum = wallet.getCanBalance() + wallet.getNocanBalance();
        return sum + "";
    }

    @Override
    public boolean verfyAliPay(HashMap<String, String> params, String out_trade_no) {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(out_trade_no);
        if (tradeOffline == null) {
            return false;
        }
        GroupPayconfig groupPayconfig = groupPayconfigMapper.selectGroupId(tradeOffline.getGroupId());
        try {
            return AlipaySignature.rsaCheckV1(params, groupPayconfig.getAliPublicKey(), Const.CHARTSET_UTF8, Const.ALIPAY_DES_TYPE_RSA);
        } catch (AlipayApiException e) {
            logger.info("=================================签名错误===================================");
            return false;
        }
    }

    @Override
    public Map<String, Object> couponList(String deskcardCode, String deskcardId, String phone, Integer tradeMoney, Integer nooffertranAmt)
            throws ApplicationException, ParseException {
        Map<String, Object> map = new HashMap<String, Object>();
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        if (device == null || device.getShopId() == null) {
            throw new ApplicationException(Rescode.FAIL, "未查询到门店记录");
        }
        Member member = memberMapper.queryNameByPhone(phone, device.getGroupId());
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "未查询到该会员信息");
        }

        // 实付金额
        Integer amount = null;
        if (nooffertranAmt == null) {
            amount = tradeMoney;
        } else {
            amount = tradeMoney - nooffertranAmt;
        }
        Date now = new Date();

        List<Map<String, Object>> userCoupons = couponUserMapper.listUserCouponsInfo(member.getId(), ActivityEnum.CouponUseStatus.Received.getType(), amount,
                ActivityEnum.ActivityPlatformType.OffLine.getType(), null);
        Iterator<Map<String, Object>> couponIterator = userCoupons.iterator();
        while (couponIterator.hasNext()) {
            Map<String, Object> couponUser = couponIterator.next();
            //优惠券是否在有效期
            if ((Integer) couponUser.get("validTimeType") == ActivityEnum.ValidTimeType.FixedTime.getType()) {
                if (now.compareTo((Date) couponUser.get("validStartTime")) < 0 || now.compareTo((Date) couponUser.get("validEndTime")) > 0) {
                    couponIterator.remove();
                    continue;
                }
            } else if ((Integer) couponUser.get("validTimeType") == ActivityEnum.ValidTimeType.AfterGet.getType()) {
                Integer days = (Integer) couponUser.get("days");
                String beginTime = DateUtil.fomatDate(new Date(), DateUtil.sdfDay);
                String  endTime = DateUtil.fomatDate(DateUtil.getDateNext((Date) couponUser.get("getTime"), days), DateUtil.sdfDay);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Date bt = sdf.parse(beginTime);
                Date et=sdf.parse(endTime);

//                Date validUseEnd = DateUtil.getDateNext((Date) couponUser.get("getTime"), days);
//					if (now.compareTo(validUseEnd) > 0) {
                if (bt.compareTo(et) > 0) {
                    couponIterator.remove();
                    continue;
                }


            } else { //其他有效日期类型无效
                couponIterator.remove();
                continue;
            }

            //优惠券在门店是否可用
            String shopIdsStr = (String) couponUser.get("shopIds");
            String[] shopIds;
            if (shopIdsStr == null) {
                couponIterator.remove();
                continue;
            } else if (shopIdsStr.equals("-1")) {    //所有门店可用
                continue;
            } else {
                shopIds = shopIdsStr.split(",");
            }
            boolean contains = false;
            for (int j = 0; j < shopIds.length; j++) {
                if (device.getShopId().equals(Long.parseLong(shopIds[j]))) {
                    contains = true;
                    break;
                }
            }
            if (!contains) {
                couponIterator.remove();
            }
            couponUser.remove("shopIds");   //移除门店信息
        }

        if (userCoupons.size() > 0) {
            map.put("couponUser_list", userCoupons);
        } else {
            throw new ApplicationException(Rescode.FAIL, "未查询到会员优惠劵");
        }
        return map;
    }

    @Override
    public Response calActualMoney(String deskcardCode, String deskcardId, String phone, Integer tradeMoney, Integer nooffertranAmt, String couponCodeStrs,
                                   Integer bonusAmount) throws ApplicationException {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        if (device == null || device.getShopId() == null) {
            throw new ApplicationException(Rescode.FAIL, "未查询到门店记录");
        }
        Member member = memberMapper.queryNameByPhone(phone, device.getGroupId());
        if (member == null) {

            throw new ApplicationException("未查询到用户记录");
        }

        Map<String, Integer> result = new HashMap<String, Integer>();

        // 需要计算的优惠金额
        Integer amount = null;
        if (nooffertranAmt == null) {
            amount = tradeMoney;
        } else {
            amount = tradeMoney - nooffertranAmt;
        }
        // 优惠券计算和锁定
        Integer couponCoverMoney = 0;
        if (!Tools.isEmpty(couponCodeStrs)) {
            String[] couponCodes = couponCodeStrs.split(",");
            for (String couponCode : couponCodes) {
                Map coupon = posApiServiceTransactional.calCoupon(couponCode, member.getId(), amount, device.getShopId());
                if (coupon != null) {
                    int value = (Integer) coupon.get("money");
                    if ((Integer) coupon.get("couponType") == ActivityEnum.CouponType.DiscountCoupon.getType()) {
                        couponCoverMoney = couponCoverMoney + (amount
                                - new BigDecimal(amount).multiply(new BigDecimal(value)).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_FLOOR).intValue());
                    } else {
                        couponCoverMoney = couponCoverMoney + value;
                    }
                } else {
                    throw new ApplicationException("优惠券不可用");
                }
            }
        }
        result.put("couponCoverMoney", couponCoverMoney);
        Date date = new Date();
        // 积分抵用金额计算

        result.put("pointCoverAmount", 0);
        result.put("bonusAmount", 0);
        int pointCoverAmount = 0;
        if (bonusAmount > 0) {
            Map<String, Integer> userCanVerifyBonus = posApiServiceTransactional.userCanVerifyBonus(device.getShopId(), member.getGroupId(), member, date,
                    tradeMoney);

            if (userCanVerifyBonus.get("pointUseMax") != 0 && bonusAmount >= userCanVerifyBonus.get("frequency_min")
                    && bonusAmount <= userCanVerifyBonus.get("pointUseMax")) {
                pointCoverAmount = new BigDecimal(bonusAmount).divide(new BigDecimal(userCanVerifyBonus.get("verifyRate")), 2, BigDecimal.ROUND_FLOOR)
                        .multiply(new BigDecimal(100)).intValue();
                if (pointCoverAmount > (tradeMoney - couponCoverMoney)) {
                    throw new ApplicationException("积分抵扣金额大于实际支付金额");
                }
                result.put("pointCoverAmount", pointCoverAmount);
                result.put("bonusAmount", bonusAmount);
            } else {
                throw new ApplicationException("积分不可核销，请重试");
            }
        }


        int realMoney = tradeMoney - couponCoverMoney - pointCoverAmount;
        realMoney = realMoney >= 0 ? realMoney : 0;
        result.put("realMoney", realMoney);
        return Response.getSuccessExtend(realMoney, result);
    }


    public Map<String, Integer> calActualMoney(String phone, Integer tradeMoney, Integer nooffertranAmt, String couponCodeStrs, Integer bonusAmount, Member member, Long shopId,
                                               Long groupId) throws ApplicationException {
        Date date = new Date();
        // 积分抵用金额计算
        Map<String, Integer> result = new HashMap<String, Integer>();
        result.put("pointCoverAmount", 0);
        result.put("bonusAmount", 0);
        int pointCoverAmount = 0;
        if (bonusAmount > 0) {
            Map<String, Integer> userCanVerifyBonus = posApiServiceTransactional.userCanVerifyBonus(shopId, member.getGroupId(), member, date,
                    tradeMoney);

            if (userCanVerifyBonus.get("pointUseMax") != 0 && bonusAmount >= userCanVerifyBonus.get("frequency_min")
                    && bonusAmount <= userCanVerifyBonus.get("pointUseMax")) {
                pointCoverAmount = new BigDecimal(bonusAmount).divide(new BigDecimal(userCanVerifyBonus.get("verifyRate")), 2, BigDecimal.ROUND_FLOOR)
                        .multiply(new BigDecimal(100)).intValue();
                result.put("pointCoverAmount", pointCoverAmount);
                result.put("bonusAmount", bonusAmount);
            } else {
                throw new ApplicationException("积分不可核销，请重试");
            }
        }

        // 需要计算的优惠金额
        Integer amount = null;
        if (nooffertranAmt == null) {
            amount = tradeMoney;
        } else {
            amount = tradeMoney - nooffertranAmt;
        }
        // 优惠券计算和锁定
        Integer couponCoverMoney = 0;
        if (!Tools.isEmpty(couponCodeStrs)) {
            String[] couponCodes = couponCodeStrs.split(",");
            for (String couponCode : couponCodes) {
                Map coupon = posApiServiceTransactional.calCoupon(couponCode, member.getId(), amount, shopId);

                if (coupon != null) {
                    int value = (Integer) coupon.get("money");
                    if ((Integer) coupon.get("couponType") == ActivityEnum.CouponType.DiscountCoupon.getType()) {
                        couponCoverMoney = couponCoverMoney + (amount
                                - new BigDecimal(amount).multiply(new BigDecimal(value)).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_FLOOR).intValue());
                    } else {
                        couponCoverMoney = couponCoverMoney + value;
                    }
                } else {
                    throw new ApplicationException("优惠券不可用");
                }
            }

        }
        logger.info("-----------------------couponCoverMoney： " + couponCoverMoney);
        logger.info("-----------------------pointCoverAmount： " + pointCoverAmount);
        logger.info("-----------------------tradeMoney： " + tradeMoney);

        result.put("couponCoverMoney", couponCoverMoney);
        int realMoney = tradeMoney - couponCoverMoney - pointCoverAmount;
        realMoney = realMoney >= 0 ? realMoney : 0;
        result.put("realMoney", realMoney);
        return result;
    }

    /**
     * 锁定优惠券和积分
     *
     * @param phone
     * @param couponCodeStrs
     * @param member
     * @param shopId
     * @param groupId
     * @param nooffertranAmt
     * @param tradeOffline
     * @throws ApplicationException
     */
    public void finishActualMoney(String phone, String couponCodeStrs, Member member, Long shopId,
                                  Long groupId, Integer nooffertranAmt, TradeOffline tradeOffline) throws ApplicationException {
        Date date = new Date();
        //积分抵用金额计算
        if (tradeOffline.getBonusAmount() != null && tradeOffline.getBonusAmount() > 0) {
            memberMapper.updateMemberBonusLock(member.getId(), tradeOffline.getBonusAmount());
            BonusVerifyLog bonusVerifyLog = new BonusVerifyLog();
            bonusVerifyLog.setGmtCreate(date);
            bonusVerifyLog.setGmtModified(date);
            bonusVerifyLog.setMemberId(member.getId());
            bonusVerifyLog.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
            bonusVerifyLog.setAdjustAmount(tradeOffline.getBonusAmount());
            bonusVerifyLog.setAdjustValue(tradeOffline.getBonusValue());
            bonusVerifyLog.setAdjustStatus(ActivityEnum.BonusVerityStatus.Locked.getType());
            bonusVerifyLog.setShopId(shopId);
            bonusVerifyLog.setMemo("创建订单锁定积分");
            bonusVerifyLog.setGroupId(member.getGroupId());
            bonusVerifyLog.setOrderId(tradeOffline.getId());

            logger.info(">>>>>>>>>>锁定结算积分开始>>>>>>");
            Integer bonusamount = tradeOffline.getBonusAmount();
            if(bonusamount != 0) {
                float settlerate = 0;
                //根据shopid获取积分结算规则
                BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopId);
                if (bonusVerifyRule != null) {//如果有门店自定义的
                    settlerate = bonusVerifyRule.getSettleRate();
                } else {//如果商圈给门店设置的
                    bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(shopId, groupId);
                    if (bonusVerifyRule != null) {
                        settlerate = bonusVerifyRule.getSettleRate();
                    } else {
                        bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
                        if (bonusVerifyRule != null) {
                            settlerate = bonusVerifyRule.getSettleRate();
                        }
                    }
                }

                //计算积分
                if (settlerate != 0) {
                    int bonus = (int) (bonusamount * settlerate / 100);
                    //积分结算给门店
                    bonusVerifyLog.setSettingAmount(bonus);
                }
            }
            logger.info(">>>>>>>>>>锁定结算积分结束>>>>>>"+bonusVerifyLog.getSettingAmount());

            bonusVerifyLogMapper.insertSelective(bonusVerifyLog);
        }



        // 需要计算的优惠金额
        Integer amount = null;
        if (nooffertranAmt == null) {
            amount = tradeOffline.getOrderAmount();
        } else {
            amount = tradeOffline.getOrderAmount() - nooffertranAmt;
        }

        //优惠券计算和锁定
        if (!Tools.isEmpty(couponCodeStrs)) {
            String[] couponCodes = couponCodeStrs.split(",");
            for (String couponCode : couponCodes) {
                Map coupon = posApiServiceTransactional.saveCalcAndLockCoupon(couponCode, member.getId(), amount, shopId, tradeOffline.getPayOrderid());
            }
        }


    }

    @Override
    public Response selectBonus(String deskcardCode, String deskcardId, String phone, Integer tranAmt, Integer nooffertranAmt) throws ApplicationException {
        // 手机号码为空 直接返回 可用积分为0
        if (Tools.isEmpty(phone)) {
            HashMap<String, Integer> userCanVerifyBonus = new HashMap<>();
            userCanVerifyBonus.put("pointUseMax", 0);// 最大可兑换积分
            userCanVerifyBonus.put("frequency_min", 0);// 最小可兑换积分
            userCanVerifyBonus.put("verifyRate", 0);// 兑换比例
            userCanVerifyBonus.put("balance", 0);
            return Response.getSuccess(userCanVerifyBonus);
        }
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        if (device == null || device.getShopId() == null) {
            throw new ApplicationException(Rescode.FAIL, "未查询到门店记录");
        }
        Member member = memberMapper.queryNameByPhone(phone, device.getGroupId());
        if (member == null) {
            Map<String, Integer> userCanVerifyBonus = new HashMap<>();
            userCanVerifyBonus.put("pointUseMax", 0);// 最大可兑换积分
            userCanVerifyBonus.put("frequency_min", 0);// 最小可兑换积分
            userCanVerifyBonus.put("verifyRate", 0);// 兑换比例
            userCanVerifyBonus.put("balance", 0);
            return Response.getSuccess(userCanVerifyBonus);
        }

        // 需要计算的优惠金额
        Integer amount = null;
        if (nooffertranAmt == null) {
            amount = tranAmt;
        } else {
            amount = tranAmt - nooffertranAmt;
        }
        Map<String, Integer> map = posApiServiceTransactional.userCanVerifyBonus(device.getShopId(), device.getGroupId(), member, new Date(), amount);

        if (member.getWalletStatus() == 1) {
            //查询用户余额
            Group group = groupMapper.selectByPrimaryKey(device.getGroupId());
            String GroupId = group.getPayGroupCode();

            try {
                String banance = queryAmount(member.getVirtualCard(), GroupId, member.getUserId());
                map.put("balance", Integer.valueOf(banance));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            map.put("balance", 0);
        }


        return Response.getSuccess(map);
    }

    public Response updateTkYcgWxPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String deskcardId, String remark, String deskcardCode,
                                     String openId, Integer actualTranAmt) throws ApplicationException {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByPrimaryKey(Long.valueOf(deskcardId));
        Long groupId = device.getGroupId();
        Member member = null;
        if (StringUtils.isNotBlank(phone)) {
            member = selectMemberInfo(groupId, phone, openId);
            if (member == null) {
                throw new ApplicationException("您输入的手机号没有查询到会员，请确认是否正确");
            }
        }
        // 插入线下交易表
        WxTkPay wxTkPay = null;
        WxTKPayResult wxTKPayResult = null;
        TradeOffline record = new TradeOffline();

        Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
        if (shop != null) {
            record.setReceiverId(shop.getId() + "");// 接收者id
            record.setReceiverName(shop.getMerchantName());// 接收者
            record.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        } else {
            throw new ApplicationException(Rescode.FAIL, "设备必须分配给子商户才能交易");
        }

        if (member == null) {
            // 表示非会员消费
            String fyMerchantCD = deviceDeskCard.getDeskcardMerchantCode();
            wxTkPay = WxTkPay.initialize(tranAmt + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "微信台卡支付", deskcardCode, openId, UtilFun.createOrderNum(Const.TK_DEVICE));
            wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
            if (!wxTKPayResult.getResult_code().equals("000000")) {
                throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
            }
            record.setMemo("台卡微信预采购支付");
            record.setTransOrderNo(wxTKPayResult.getMchnt_order_no());
            record.setDiscountAmount(0);// 折扣金额
            record.setRealAmount(tranAmt);// 实付金额

        } else {
            // 表示会员
            record.setPayerId(member.getId());// 会员id
            record.setPayerName(member.getName());
            record.setPayerType(((byte) CommonEnum.UserType.User.getType()));

            // 这个表示
            ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(device.getGroupId(), device.getShopId());
            if (shopGroupRelation != null && new Integer(1).equals(shopGroupRelation.getPrePurchaseStatus())) {
                // 表示处于预采购中
                PrePurchaseActivity prePurchaseActivity = prePurchaseActivityMapper.findInPrePurchaseActivity(device.getShopId(), groupId);
                // 查询渠道的收款账户
                if (prePurchaseActivity == null) {
                    throw new ApplicationException(Rescode.FAIL, "商户状态不正确");
                }

                int acturlAmount = tranAmt * prePurchaseActivity.getCustomerBenefitAmount() / 100;
                GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(groupId);
                String fyMerchantCD = groupReceiveInfo.getMerchantCode();
                wxTkPay = WxTkPay.initialize(acturlAmount + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "微信台卡支付", deskcardCode, openId, UtilFun.createOrderNum(Const.TK_DEVICE));
                wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
                if (!wxTKPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
                }
                record.setMemo("Prepurchase");
                record.setTransOrderNo(wxTKPayResult.getMchnt_order_no());
                record.setDiscountAmount(tranAmt - acturlAmount);// 折扣金额
                record.setRealAmount(acturlAmount);// 实付金额
                record.setPrepurActivityId(prePurchaseActivity.getId());

            } else {
                // 正常子商户高迁
                String fyMerchantCD = deviceDeskCard.getDeskcardMemMerchantCode();
                wxTkPay = WxTkPay.initialize(tranAmt + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "微信台卡支付", deskcardCode, openId, UtilFun.createOrderNum(Const.TK_DEVICE));
                wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
                if (!wxTKPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
                }
                record.setMemo("台卡微信预采购支付");
                record.setDiscountAmount(0);// 折扣金额
                record.setRealAmount(tranAmt);// 实付金额
                record.setTransOrderNo(wxTKPayResult.getMchnt_order_no());
            }
        }
        record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
        record.setGroupId(groupId);
        record.setOrderId(wxTkPay.getOutOrderNum());
        record.setPayOrderid(wxTkPay.getOutOrderNum());
        record.setPayerType((byte) CommonEnum.UserType.User.getType()); // 付款者类型(枚举)
        record.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        record.setSubType((byte) BizEnum.PaymentScene.DeskCard.getType());// 支付场景
        record.setOrderAmount(tranAmt); // 订单金额
        record.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        record.setIsWallet(false);
        record.setTermSerial(deskcardCode);// 设备序列号
        record.setMerchantNo(wxTkPay.getFyMerchantCD());// 商户号
        record.setTerminalNo(deskcardCode);// 商户终端号
        record.setTransNo(null); // 交易流水号
        record.setTransOrderNo(null);// 交易机构订单号
        record.setPayAccount("");// 支付卡号
        record.setScanOrganization(deviceDeskCard.getDeskcardOrganization());// 扫码付入网机构
        record.setOldOrderId(null);
        record.setDividableAmount(0);// 可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayBakOrderid(null);

        record.setInNetCompany(deviceDeskCard.getDeskcardOrganization());// 入网机构

        StringBuffer detail = new StringBuffer();
        detail.append("&appId=").append(wxTKPayResult.getSdk_appid()).append("&timeStamp=").append(wxTKPayResult.getSdk_timestamp()).append("&nonceStr=")
                .append(wxTKPayResult.getSdk_noncestr()).append("&package=").append(wxTKPayResult.getSdk_package()).append("&signType=")
                .append(wxTKPayResult.getSdk_signtype()).append("&paySign=").append(wxTKPayResult.getSdk_paysign());
        record.setDetail(detail.toString());// 详情
        record.setCrcodeStr(wxTKPayResult.getQr_code());
//		record.setPayOrderid(wxTKPayResult.getMchnt_order_no());
        tradeOfflineMapper.insertSelective(record);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("appId", wxTKPayResult.getSdk_appid());
        resultMap.put("timeStamp", wxTKPayResult.getSdk_timestamp());
        resultMap.put("nonceStr", wxTKPayResult.getSdk_noncestr());
        resultMap.put("package", wxTKPayResult.getSdk_package());
        resultMap.put("signType", wxTKPayResult.getSdk_signtype());
        resultMap.put("paySign", wxTKPayResult.getSdk_paysign());
        return Response.getSuccess(resultMap);

    }

    //用户进行钱包消费
    @Override
    public Response updateTkYcgAliPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String deskcardId, String remark,
                                      String deskcardCode, Integer actualTranAmt) throws ApplicationException {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByPrimaryKey(Long.valueOf(deskcardId));
        Long groupId = device.getGroupId();
        Member member = null;
        if (StringUtils.isNotBlank(phone)) {
            member = selectMemberInfo(groupId, phone, null);
            if (member == null) {
                throw new ApplicationException("您输入的手机号没有查询到会员，请确认是否正确");
            }
        }
        // 插入线下交易表
        AliTkPay aliTkPay = null;
        AliTKPayResult aliTKPayResult = null;
        TradeOffline record = new TradeOffline();
        Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
        if (shop != null) {
            record.setReceiverId(shop.getId() + "");// 接收者id
            record.setReceiverName(shop.getMerchantName());// 接收者
            record.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        } else {
            throw new ApplicationException(Rescode.FAIL, "设备必须分配给子商户才能交易");
        }
        if (member == null) {
            // 表示非会员消费
            String fyMerchantCD = deviceDeskCard.getDeskcardMerchantCode();
            aliTkPay = AliTkPay.initialize(tranAmt + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "支付宝台卡消费", UtilFun.createOrderNum(Const.TK_DEVICE), deskcardCode);
            aliTKPayResult = IPayAPI.finishAliTkPay(aliTkPay);
            if (!aliTKPayResult.getResult_code().equals("000000")) {
                throw new ApplicationException(Rescode.FAIL, "支付宝调用失败" + aliTKPayResult.getResult_msg());
            }
            record.setMemo("台卡支付宝支付");
            record.setDiscountAmount(0);// 折扣金额
            record.setRealAmount(tranAmt);// 实付金额
            record.setTransOrderNo(aliTKPayResult.getMchnt_order_no());
        } else {
            // 表示会员
            record.setPayerId(member.getId());// 会员id
            record.setPayerName(member.getName());
            record.setPayerType(((byte) CommonEnum.UserType.User.getType()));
            // 这个表示
            ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(device.getGroupId(), device.getShopId());
            if (shopGroupRelation != null && new Integer(1).equals(shopGroupRelation.getPrePurchaseStatus())) {
                // 表示处于预采购中
                PrePurchaseActivity prePurchaseActivity = prePurchaseActivityMapper.findInPrePurchaseActivity(device.getShopId(), groupId);
                // 查询渠道的收款账户
                if (prePurchaseActivity == null) {
                    throw new ApplicationException(Rescode.FAIL, "商户状态不正确");
                }

                int acturlAmount = tranAmt * prePurchaseActivity.getCustomerBenefitAmount() / 100;
                GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(groupId);
                String fyMerchantCD = groupReceiveInfo.getMerchantCode();
                aliTkPay = AliTkPay.initialize(tranAmt + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "支付宝台卡消费", UtilFun.createOrderNum(Const.TK_DEVICE), deskcardCode);
                aliTKPayResult = IPayAPI.finishAliTkPay(aliTkPay);
                if (!aliTKPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL, "支付宝调用失败" + aliTKPayResult.getResult_msg());
                }
                record.setTransOrderNo(aliTKPayResult.getMchnt_order_no());
                record.setMemo("Prepurchase");
                record.setDiscountAmount(tranAmt - acturlAmount);// 折扣金额
                record.setRealAmount(acturlAmount);// 实付金额
                record.setPrepurActivityId(prePurchaseActivity.getId());

            } else {
                // 正常子商户高迁
                String fyMerchantCD = deviceDeskCard.getDeskcardMemMerchantCode();
                aliTkPay = AliTkPay.initialize(tranAmt + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, "支付宝台卡充值", UtilFun.createOrderNum(Const.TK_DEVICE), deskcardCode);
                aliTKPayResult = IPayAPI.finishAliTkPay(aliTkPay);
                if (!aliTKPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL, "支付宝调用失败" + aliTKPayResult.getResult_msg());
                }
                record.setTransOrderNo(aliTKPayResult.getMchnt_order_no());
                record.setMemo("台卡支付宝支付");
                record.setDiscountAmount(0);// 折扣金额
                record.setRealAmount(tranAmt);// 实付金额
            }
        }
        record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
        record.setGroupId(groupId);
        record.setPayOrderid(aliTkPay.getOutOrderNum());
        record.setOrderId(aliTkPay.getOutOrderNum());
        record.setPayerType((byte) CommonEnum.UserType.User.getType()); // 付款者类型(枚举)
        record.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        record.setSubType((byte) BizEnum.PaymentScene.DeskCard.getType());// 支付场景
        record.setOrderAmount(tranAmt); // 订单金额
        record.setPayType((byte) BizEnum.PaymentType.AliPay.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        record.setIsWallet(false);
        record.setTermSerial(deskcardCode);// 设备序列号
        record.setMerchantNo(aliTkPay.getFyMerchantCD());// 商户号
        record.setTerminalNo(deskcardCode);// 商户终端号
        record.setTransNo(null); // 交易流水号
        record.setTransOrderNo(aliTKPayResult.getMchnt_order_no());// 交易机构订单号
        record.setPayAccount("");// 支付卡号
        record.setScanOrganization(deviceDeskCard.getDeskcardOrganization());// 扫码付入网机构
        record.setOldOrderId(null);
        record.setDividableAmount(0);// 可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayBakOrderid(null);
        record.setInNetCompany(deviceDeskCard.getDeskcardOrganization());// 入网机构
        record.setDetail(aliTKPayResult.getQr_code());// 详情
        record.setCrcodeStr(aliTKPayResult.getQr_code());
        tradeOfflineMapper.insertSelective(record);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("qr_code", aliTKPayResult.getQr_code());
        return Response.getSuccess(resultMap);
    }

    @Override
    public PrePurchaseActivity findPrePurchaseActivity(String deskcardCode, String deskcardId) {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.parseLong(deskcardId));
        if (device.getShopId() == null) {
            return null;
        }
        Long groupId = device.getGroupId();
        Long shopId = device.getShopId();
        ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(groupId, shopId);
        if (shopGroupRelation.getPrePurchaseStatus() == 1) {
            //
            return prePurchaseActivityMapper.findInPrePurchaseActivity(shopId, groupId);
        }
        return null;
    }

    @Override
    public Map<String, Object> getServiceOrderDetailByOrderId(String groupId, String openId, String memberId, String orderId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (Tools.isEmpty(orderId)) {
            throw new ApplicationException(Rescode.FAIL, "orderId 不能为空！");
        }

        OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByOrderNo(orderId);
        if (orderServiceGood == null) {
            throw new ApplicationException("没查到服务订单");
        }
        MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());
        map.put("good_name", orderServiceGood.getGoodName());
        map.put("good_valid_time", DateUtil.fomatDate(mallGood.getValidDate(), DateUtil.sdfDay));
        map.put("good_number", orderServiceGood.getNumber());

        List<OrderServiceGoodDetail> details = orderServiceGoodDetailMapper.queryOrderServiceDetailById(orderId, null);
        List<Map<String, Object>> goodList = new ArrayList<Map<String, Object>>();
        for (OrderServiceGoodDetail detail : details) {
            Map<String, Object> goodMap = new HashMap<String, Object>();
            goodMap.put("detail_id", detail.getId());
            goodMap.put("coupon_code", detail.getCouponCode());
            // 获取券码二维码base64字符流
            String couponQrcodestr = CodeUtil.getBase64QRcodeStr(QRCodeParams.initialize(detail.getCouponCode(), 400, 400, 0xFF000000, 0xFFFFFFFF, 2, null));
            goodMap.put("coupon_qrcode", couponQrcodestr);
            goodList.add(goodMap);
        }
        if (goodList.size() > 0) {
            map.put("good_list", goodList);
        }
        // 查询可核销门店列表
        List<Shop> shops = shopMapper.selectCanVerifyShopListByServiceGoodId(orderServiceGood.getGoodId());
        List<Map<String, Object>> shopList = new ArrayList<Map<String, Object>>();
        for (Shop shop : shops) {
            Map<String, Object> shopMap = new HashMap<String, Object>();
            shopMap.put("shop_id", shop.getId());
            shopMap.put("shop_name", shop.getMerchantName());
            shopMap.put("work_time", shop.getWorkTime());
            shopMap.put("shop_phone", shop.getPhone());
            shopMap.put("shop_address", shop.getAddress());
            shopList.add(shopMap);
        }
        if (shopList.size() > 0) {
            map.put("shop_list", shopList);
        }
        return map;
    }

    @Override
    public TradeOffline findOrderId(String orderId, Integer transactionStatus) throws Exception {
        TradeOffline record = tradeOfflineMapper.selectByOrderIdStatus(orderId, (byte) transactionStatus.intValue());
        return record;
    }

    @Override
    public Response updateObdWxPay(String orderId, Integer realAmount, String remark, String openId, String mchCreateIp, String notifyUrl)
            throws ApplicationException {
        TradeOffline record = tradeOfflineMapper.selectByOrderIdStatus(orderId, (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        if (record == null) {
            throw new ApplicationException("没查到该笔待支付订单");
        }
        GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(record.getGroupId());
        if (groupReceiveInfo == null) {
            throw new ApplicationException("请完成obd收款设置");
        }
        String fyMerchantCD = groupReceiveInfo.getMerchantCode();
        record.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
        record.setRealAmount(realAmount);// 实付金额
        record.setOrderAmount(realAmount); // 订单金额
        record.setDiscountAmount(0);// 折扣金额
        record.setSubType((byte) BizEnum.PaymentScene.DeskCard.getType());// 支付场景
        record.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
        record.setGmtModified(new Date());
        record.setPayerType((byte) CommonEnum.UserType.Agents.getType()); // 付款者类型(枚举)
        record.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        record.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        record.setIsWallet(false);
        record.setMemo(remark);
        record.setMerchantNo(fyMerchantCD);// 商户号
        record.setDividableAmount(0);// 可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setTerminalNo(groupReceiveInfo.getTerminalCode());// 商户终端号
        WxTkPay wxTkPay = WxTkPay.initialize(realAmount + "", null, mchCreateIp, null, notifyUrl, fyMerchantCD, "微信台卡obd支付",
                groupReceiveInfo.getTerminalCode(), openId, UtilFun.createOrderNum(Const.TK_DEVICE));
        WxTKPayResult wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
        if (!wxTKPayResult.getResult_code().equals("000000")) {
            throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
        }
        StringBuffer detail = new StringBuffer();
        detail.append("&appId=").append(wxTKPayResult.getSdk_appid()).append("&timeStamp=").append(wxTKPayResult.getSdk_timestamp()).append("&nonceStr=")
                .append(wxTKPayResult.getSdk_noncestr()).append("&package=").append(wxTKPayResult.getSdk_package()).append("&signType=")
                .append(wxTKPayResult.getSdk_signtype()).append("&orderNo=").append(wxTKPayResult.getMchnt_order_no()).append("&paySign=")
                .append(wxTKPayResult.getSdk_paysign());
        record.setOrderId(wxTkPay.getOutOrderNum());
        record.setPayOrderid(wxTkPay.getOutOrderNum());
        record.setTransNo(wxTkPay.getOutOrderNum());// 交易流水号
        record.setDetail(detail.toString());// 详情
        record.setCrcodeStr(wxTKPayResult.getQr_code());
        record.setTransOrderNo(wxTKPayResult.getMchnt_order_no());

        tradeOfflineMapper.updateByPrimaryKeySelective(record);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("appId", wxTKPayResult.getSdk_appid());
        resultMap.put("timeStamp", wxTKPayResult.getSdk_timestamp());
        resultMap.put("nonceStr", wxTKPayResult.getSdk_noncestr());
        resultMap.put("package", wxTKPayResult.getSdk_package());
        resultMap.put("signType", wxTKPayResult.getSdk_signtype());
        resultMap.put("paySign", wxTKPayResult.getSdk_paysign());
        return Response.getSuccess(resultMap);

    }

    @Override
    public Response updateObdAliPay(String orderId, Integer realAmount, String remark, String mchCreateIp, String notifyUrl) throws ApplicationException {
        TradeOffline record = tradeOfflineMapper.selectByOrderIdStatus(orderId, (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        if (record == null) {
            throw new ApplicationException("没查到该笔待支付订单");
        }
        GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(record.getGroupId());
        if (groupReceiveInfo == null) {
            throw new ApplicationException("没查到该商户信息");
        }
        String fyMerchantCD = groupReceiveInfo.getMerchantCode();
        record.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
        record.setRealAmount(realAmount);// 实付金额
        record.setOrderAmount(realAmount); // 订单金额
        record.setDiscountAmount(0);// 折扣金额
        record.setSubType((byte) BizEnum.PaymentScene.DeskCard.getType());// 支付场景
        record.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
        record.setGmtModified(new Date());
        record.setPayerType((byte) CommonEnum.UserType.Agents.getType()); // 付款者类型(枚举)
        record.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        record.setPayType((byte) BizEnum.PaymentType.AliPay.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        record.setIsWallet(false);
        record.setMemo(remark);
        record.setMerchantNo(fyMerchantCD);// 商户号
        record.setDividableAmount(0);// 可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setTerminalNo(groupReceiveInfo.getTerminalCode());// 商户终端号
        AliTkPay aliTkPay = AliTkPay.initialize(realAmount + "", null, mchCreateIp, "13888888888", notifyUrl, fyMerchantCD, "支付宝台卡充值",
                UtilFun.createOrderNum(Const.TK_DEVICE), groupReceiveInfo.getTerminalCode());
        AliTKPayResult aliTKPayResult = IPayAPI.finishAliTkPay(aliTkPay);
        if (!aliTKPayResult.getResult_code().equals("000000")) {
            throw new ApplicationException(Rescode.FAIL, "支付宝调用失败" + aliTKPayResult.getResult_msg());
        }
        // record.setOrderId(aliTkPay.getOutOrderNum());
        record.setTransNo(aliTkPay.getOutOrderNum());// 交易流水号
        record.setDetail(aliTKPayResult.getQr_code());// 详情
        record.setCrcodeStr(aliTKPayResult.getQr_code());
        record.setPayOrderid(aliTKPayResult.getMchnt_order_no());
        record.setTransOrderNo(aliTKPayResult.getMchnt_order_no());// 交易机构订单号
        tradeOfflineMapper.updateByPrimaryKeySelective(record);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("qr_code", aliTKPayResult.getQr_code());
        return Response.getSuccess(resultMap);
    }

    public Map<String, Object> getBonusInfo(String groupId, String openId, String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        BonusUserInfoDTO bonusUserInfoDTO = statisMemberMapper.selectBonusInfo(Long.parseLong(memberId));
        if (bonusUserInfoDTO == null)
            throw new ApplicationException("查询会员：" + memberId + "积分信息失败！");

        map.put("bonusAmount", bonusUserInfoDTO.getBonusAmount());
        map.put("bonusFreeze", bonusUserInfoDTO.getBonusFreeze());
        map.put("bonusNum", bonusUserInfoDTO.getBonusNum());
        map.put("bonusValue", bonusUserInfoDTO.getBonusValue());
        map.put("todayBonusAmount", bonusUserInfoDTO.getTodayBonusAmount());

        return map;
    }

    public Map<String, Object> getBonusInfoDetail(String groupId, String openId, String memberId, String startDate, String endDate, Integer pageNo,
                                                  Integer pageSize) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (pageNo == null) {
            throw new ApplicationException(Rescode.FAIL, "pageNo 不能为空！");
        }
        if (pageSize == null) {
            throw new ApplicationException(Rescode.FAIL, "pageSize 不能为空！");
        }

        Map<String, Object> param = new HashMap<String, Object>();
        // 取得门店数据；
        param.clear();
        param.put("memberId", Long.parseLong(memberId));
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("start", pageSize * (pageNo - 1));
        param.put("limit", pageSize);

        List<BonusSendLog> bonusSendLogs = bonusSendLogMapper.selectMemberBonusLog(param);
        List<Map<String, Object>> bonusLogList = new ArrayList<Map<String, Object>>();
        for (BonusSendLog bonusSendLog : bonusSendLogs) {
            Map<String, Object> logMap = new HashMap<String, Object>();
            logMap.put("date", DateUtil.fomatDate(bonusSendLog.getGmtModified(), DateUtil.sdfDay));
            if (bonusSendLog.getIsFlag() == 1) {// 核销
                logMap.put("send_type", ActivityEnum.BonusVerityType.fromType(bonusSendLog.getSendType()).getName() + "("
                        + ActivityEnum.BonusVerityStatus.fromType(bonusSendLog.getAdjustStatus()).getName() + ")");
            } else {// 发放
                logMap.put("send_type", ActivityEnum.BonusSendType.fromType(bonusSendLog.getSendType()).getName() + "("
                        + ActivityEnum.BonusSendStatus.fromType(bonusSendLog.getAdjustStatus()).getName() + ")");
            }
            logMap.put("bonus_amount", bonusSendLog.getAdjustAmount());
            bonusLogList.add(logMap);
        }
        if (bonusLogList.size() > 0) {
            map.put("bonuslog_List", bonusLogList);
        }
        return map;
    }

    @Override
    public Map<String, Object> getBonusRule(String groupId, String openId) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        //发放 判断有没有设置行业规则
//		int count = bonusSendRuleMapper.queryBonusSendRuleCount(Long.parseLong(groupId));
        //有设置行业规则
        List<Map<String, Object>> sendRuleList = new ArrayList<Map<String, Object>>();
//		if(count>0){
//			List<BonusSendRule> bonusSendRuleList =bonusSendRuleMapper.queryBonusSendRuleList(Long.parseLong(groupId));
//			for (BonusSendRule bonusSendRule : bonusSendRuleList) {
//				Map<String, Object> sendruleMap = new HashMap<String, Object>();
//				//写死 告诉前端 方便处理 这是已经设置行业规则的
//				sendruleMap.put("type",1);
//				sendruleMap.put("industryName",bonusSendRule.getIndustryName());
//				sendruleMap.put("send_day_max",bonusSendRule.getSendDayMax());
//				sendruleMap.put("send_single_max",bonusSendRule.getSendSingleMax());
//				sendruleMap.put("send_day_count",bonusSendRule.getSendDayCount());
//				sendruleMap.put("send_accounted_time",bonusSendRule.getSendAccountedTime());
//				sendruleMap.put("send_time_type",bonusSendRule.getSendTimeType());//发放时间leixing
//				sendRuleList.add(sendruleMap);
//			}
//			if (sendRuleList.size() > 0) {
//				map.put("bonusSendRule_List", sendRuleList);
//			}
//		}else{
        BonusSendRule bonusSendRule = bonusSendRuleMapper.queryBonusSendRule(Long.parseLong(groupId));
        Map<String, Object> sendruleMap2 = new HashMap<String, Object>();
        sendruleMap2.put("type", 0);
        sendruleMap2.put("send_day_max", bonusSendRule.getSendDayMax());
        sendruleMap2.put("send_single_max", bonusSendRule.getSendSingleMax());
        sendruleMap2.put("send_day_count", bonusSendRule.getSendDayCount());
        sendruleMap2.put("send_accounted_time", bonusSendRule.getSendAccountedTime());
        sendruleMap2.put("send_time_type", bonusSendRule.getSendTimeType());//发放时间leixing
        sendRuleList.add(sendruleMap2);
        if (sendRuleList.size() > 0) {
            map.put("bonusSendRule_List", sendRuleList);
        }
//		}

        //核销
        //发放 判断有没有设置行业规则
        List<Map<String, Object>> veriftyRuleList = new ArrayList<Map<String, Object>>();
//		int count2 = bonusVerifyRuleMapper.queryBonusVeriftyRuleCount(Long.parseLong(groupId));
//		if(count2>0){
//			List<BonusVerifyRule> bonusVerifyRuleList =bonusVerifyRuleMapper.queryBonusVeriftyRuleList(Long.parseLong(groupId));
//			for (BonusVerifyRule bonusVerifyRule : bonusVerifyRuleList) {
//				Map<String, Object> veriftyruleMap = new HashMap<String, Object>();
//				//写死 告诉前端 方便处理 这是已经设置行业规则的
//				veriftyruleMap.put("type",1);
//				veriftyruleMap.put("verify_rate",bonusVerifyRule.getVerifyRate());
//				veriftyruleMap.put("industryName",bonusVerifyRule.getIndustryName());
//				veriftyruleMap.put("verify_single_min_type",bonusVerifyRule.getVerifySingleMinType());
//				veriftyruleMap.put("verify_single_min",bonusVerifyRule.getVerifySingleMin());
//				veriftyruleMap.put("verify_single_max_type",bonusVerifyRule.getVerifySingleMaxType());
//				veriftyruleMap.put("verify_single_max",bonusVerifyRule.getVerifySingleMax());
//				veriftyruleMap.put("verify_day_count",bonusVerifyRule.getVerifyDayCount());
//				veriftyruleMap.put("verify_day_sum",bonusVerifyRule.getVerifyIndustry());
//				if(bonusVerifyRule.getVerifyTimeType()==1){
//					veriftyruleMap.put("verify_time_from",bonusVerifyRule.getVerifyTimeFrom1());
//					veriftyruleMap.put("verify_time_to",bonusVerifyRule.getVerifyTimeTo1());
//				}else if(bonusVerifyRule.getVerifyTimeType()==2){
//					veriftyruleMap.put("verify_time_from",bonusVerifyRule.getVerifyTimeFrom2());
//					veriftyruleMap.put("verify_time_to",bonusVerifyRule.getVerifyTimeTo2());
//				}else{
//					veriftyruleMap.put("verify_time_from",bonusVerifyRule.getVerifyTimeFrom3());
//					veriftyruleMap.put("verify_time_to",bonusVerifyRule.getVerifyTimeTo3());
//				}
//				veriftyRuleList.add(veriftyruleMap);
//			}
//			if (veriftyRuleList.size() > 0) {
//				map.put("bonusVerifyRule_List", veriftyRuleList);
//			}
//		}else{
        BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.queryBonusVeriftyRule(Long.parseLong(groupId));
        Map<String, Object> veriftyruleMap2 = new HashMap<String, Object>();
        veriftyruleMap2.put("type", 0);
        veriftyruleMap2.put("verify_rate", bonusVerifyRule.getVerifyRate());
        veriftyruleMap2.put("verify_single_min_type", bonusVerifyRule.getVerifySingleMinType());
        veriftyruleMap2.put("verify_single_min", bonusVerifyRule.getVerifySingleMin());
        veriftyruleMap2.put("verify_single_max_type", bonusVerifyRule.getVerifySingleMaxType());
        veriftyruleMap2.put("verify_single_max", bonusVerifyRule.getVerifySingleMax());
        veriftyruleMap2.put("verify_day_count", bonusVerifyRule.getVerifyDayCount());
        veriftyruleMap2.put("verify_day_sum", bonusVerifyRule.getVerifyDaySum());
        veriftyRuleList.add(veriftyruleMap2);
        if (veriftyRuleList.size() > 0) {
            map.put("bonusVerifyRule_List", veriftyRuleList);
        }
//		}

        return map;
    }

    @Override
    public Response updateWalletPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String deskcardId, String remark, String deskcardCode,
                                    String payPwd, Integer actualTranAmt, Integer nooffertranAmt, String couponCodes, Integer bonusAmount, String rootHomeUrl) throws ApplicationException, ExecutionException, InterruptedException {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
        DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByPrimaryKey(Long.valueOf(deskcardId));

        Long groupId = device.getGroupId();
        Long shopId = device.getShopId();


        Member member = null;
        if (StringUtils.isNotBlank(phone)) {
            member = selectMemberInfo(groupId, phone, null);
            if (member == null) {
                return Response.getError("您输入的手机号没有查询到会员，请确认是否正确");
            }
        }
        if (member == null) {
            return Response.getError("会员信息不存在");
        }
        if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
            return Response.getError("支付密码错误");
        }


        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(groupId, shop.getId());
        if (shopGroupRelation == null) {
            throw new ApplicationException(Rescode.FAIL, "商户配置信息不存在");
        }

        Map<String, Integer> selectTranAmt = calActualMoney(phone, tranAmt, nooffertranAmt, couponCodes, bonusAmount, member, shopId, groupId);
        Integer actualMoney = selectTranAmt.get("realMoney");
        if (!actualTranAmt.equals(actualMoney)) {
            throw new ApplicationException(Rescode.FAIL, "实付金额不一致" + selectTranAmt);
        }
        String orgOrderNum = UtilFun.createOrderNum(Const.TK_DEVICE);
        String MerchantId = shopGroupRelation.getPayMerchantCode();
        TradeOffline record = finishInitTradeOff(groupId, BizEnum.PaymentType.Wallet, member, shop, deskcardCode, MerchantId, deviceDeskCard);
        logger.info("=====record1======" + record);
        //初始化金额相关
        Integer pointCoverAmount = selectTranAmt.get("pointCoverAmount");
        initTradeAmt(record, tranAmt, actualMoney, selectTranAmt.get("couponCoverMoney"), bonusAmount, pointCoverAmount);
        if (actualMoney == 0) {
            record.setOrderId(orgOrderNum);
            record.setPayOrderid(orgOrderNum);
            return finishZroeAmount1(member, shop, record, phone, nooffertranAmt, couponCodes, rootHomeUrl);

        } else {
            record.setTransNo(DateUtil.getSdfTimes() + Tools.getRandomNum(4)); //交易流水号
            String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();

//	        PayResult payResult =walletService.updatePayConsumption(member.getVirtualCard(), payGroupCode, member.getUserId(), actualTranAmt, orgOrderNum, payPwd,MerchantId,orgOrderNum);
//			if (!payResult.getRespCode().equals("0000")) {
//				throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
//			}
            //异步去更新钱包信息
            PayResult payResult = posApiService.synUpdatePayConsumption(member.getVirtualCard(), payGroupCode, member.getUserId(), actualTranAmt, orgOrderNum, payPwd, MerchantId, orgOrderNum);

            logger.info("============== 异步调用结束");
            System.out.print(payResult);
            if (!payResult.getRespCode().equals("0000")) {
                throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
            }


            logger.info("-----------------------钱包交易手续费" + payResult.getMerchantFee());
            record.setDividableAmount(SysUtils.Object2Integer(payResult.getMerchantFee()));//可分润金额
            record.setFee(SysUtils.Object2Integer(payResult.getMerchantFee()));
            record.setShopFee(Tools.isEmpty(payResult.getMerchantFee()) ? 0 : Integer.valueOf(payResult.getMerchantFee()));
            record.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            record.setTransOrderNo(payResult.getOrderId());
            record.setPayOrderid(orgOrderNum);
            record.setOrderId(orgOrderNum);
            tradeOfflineMapper.insertSelective(record);
        }

        //锁定积分和优惠券
        finishActualMoney(phone, couponCodes, member, shopId, groupId, nooffertranAmt, record);
        //完成 积分和优惠券的核销  replace
        posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(record, couponCodes, shop.getId());
        if (record.getReceiverType() == CommonEnum.UserType.Store.getType()) {
            posApiService.memberShopRelation(member.getId(), shop.getId(), record.getGmtCreate(), record.getOrderAmount());
        }

        posApiService.saveSynNewBenefitCalc(shop.getId(), record.getRealAmount(), record.getGroupId(), member, record.getPayOrderid(), record.getId());

        logger.info("--准备发送模板消息--");
        try {
            templateMailSendService.sendTemplate(record, BizEnum.WebTemplateType.template11.getType(), record.getPayerId(),
                    record.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("--模板消息发送失败--" + e);
        }

        if (shopId != null) {
            //推送交易信息给APP
            Userbase userbase = shopMapper.getUserNameByShopId(shopId);
            //发送推送信息
            Notice notice = new Notice();
            try {
                notice.setNoticetype(0);
                notice.setSender(member.getGroupId());
                notice.setReceiver(userbase.getUsername());
                notice.setNoticetitle("您有一笔新的收入");
                notice.setNoticetarget("ACCOUNT");
                notice.setNoticebody(BizEnum.PaymentType.fromType(record.getPayType()).getName() + "收入" + Double.parseDouble(actualMoney + "") / 100 + "元");
                notice.setGroupid(member.getGroupId());
                notice.setNoticestatus(1);
                notice.setIsplay(1);
                notice.setType(4);
                notice.setTvalue(record.getId() + "#" + (record.getPayerId() != null ? record.getPayerId() : 0));
                appNoticeService.sendNoticeToUsers(notice);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //结算积分给门店 start
/*        Integer bonusamount = record.getBonusAmount();
        if (bonusamount != 0) {
            float settlerate = 0;
            //根据shopid获取积分结算规则
            BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopId);
            if (bonusVerifyRule != null) {//如果有门店自定义的
                settlerate = bonusVerifyRule.getSettleRate();
            } else {//如果商圈给门店设置的
                bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(shopId, groupId);
                if (bonusVerifyRule != null) {
                    settlerate = bonusVerifyRule.getSettleRate();
                } else {
                    bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
                    if (bonusVerifyRule != null) {
                        settlerate = bonusVerifyRule.getSettleRate();
                    }
                }
            }

            //计算积分
            if (settlerate != 0) {
                int bonus = (int) (bonusamount * settlerate / 100);
                //积分结算给门店
                bonusVerifyShopMapper.insertShopVerifyBonus(groupId, shopId, bonus);

                //添加积分结算记录
                BonusVerifyLog record1 = new BonusVerifyLog();
                record1.setGroupId(groupId);
                record1.setMemberId(member.getId());
                record1.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
                record1.setAdjustAmount(bonus);
                record1.setShopId(shopId);
                record1.setOrderId(record.getId());
                record1.setAdjustStatus(ActivityEnum.BonusVerityStatus.OutAccounted.getType());
                bonusVerifyLogMapper.insert(record1);
            }
        }
        //结算积分给门店 end*/

        logger.info("=====record======" + record);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (record != null) {
            resultMap.put("tradeId", record.getId() == null ? "" : record.getId());
        }
        if (member != null) {
            resultMap.put("memberId", member.getId() == null ? "" : member.getId());
        }
        if (shop != null) {
            resultMap.put("shopId", shop.getId() == null ? "" : shop.getId());
        }
        Response response = Response.getSuccessExtend(resultMap, record);
        return response;
    }


    @Override
    public Response updateWalletYcgPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String deskcardId, String string,
                                       String deskcardCode, String payPwd, Integer actualTranAmt) throws ApplicationException {
        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
//		DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByPrimaryKey(Long.valueOf(deskcardId));

        Long groupId = device.getGroupId();

        TradeOffline record = new TradeOffline();
        Member member = null;
        if (StringUtils.isNotBlank(phone)) {
            member = selectMemberInfo(groupId, phone, null);
            if (member == null) {
                throw new ApplicationException("您输入的手机号没有查询到会员，请确认是否正确");
            }
        }
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
            throw new ApplicationException(Rescode.FAIL, "支付密码错误");
        }
        record.setPayerId(member.getId());//会员id
        record.setPayerName(member.getName());
        record.setPayerType(((byte) CommonEnum.UserType.User.getType()));

        Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
        ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(groupId, shop.getId());
        if (shopGroupRelation == null) {
            throw new ApplicationException(Rescode.FAIL, "商户配置信息不存在");
        }
        String MerchantId = null;
        PrePurchaseActivity prePurchaseActivity = null;
        if (shopGroupRelation.getPrePurchaseStatus() == 1) {//预采购
            // 表示处于预采购中
            prePurchaseActivity = prePurchaseActivityMapper.findInPrePurchaseActivity(device.getShopId(), groupId);
            // 查询渠道的收款账户
            if (prePurchaseActivity == null) {
                throw new ApplicationException(Rescode.FAIL, "商户状态不正确");
            }
            int acturlAmount = tranAmt * prePurchaseActivity.getCustomerBenefitAmount() / 100;
            record.setMemo("Prepurchase");
            record.setDiscountAmount(tranAmt - acturlAmount);// 折扣金额
            record.setRealAmount(acturlAmount);// 实付金额
            record.setPrepurActivityId(prePurchaseActivity.getId());
        } else {
            MerchantId = shopGroupRelation.getPayMerchantCode();
            record.setRealAmount(actualTranAmt);//实付金额
            record.setDiscountAmount(tranAmt - actualTranAmt);//折扣金额
            record.setMemo("钱包台卡支付");
        }
        record.setReceiverId(shop.getId() + "");//接收者id
        record.setReceiverName(shop.getMerchantName());//接收者
        //插入线下交易表
        String orderId = UtilFun.createOrderNum();
        record.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
        record.setGroupId(groupId);
        record.setOrderId(orderId);
        record.setPayerId(member.getId());//付款者id号
        record.setPayerName(member.getName());//付款者姓名
        record.setPayerType((byte) CommonEnum.UserType.User.getType());
        record.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        record.setSubType((byte) BizEnum.PaymentScene.DeskCard.getType());//支付场景
        record.setOrderAmount(tranAmt); //订单金额
        record.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        record.setIsWallet(true);
        record.setTermSerial(null);
        record.setMerchantNo(null);//商户号
        record.setTerminalNo(null);//商户终端号

        record.setPayAccount("");//支付卡号
        record.setScanOrganization((byte) BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
        record.setOldOrderId(null);

        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayBakOrderid(null);
        record.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());//入网机构
        record.setDetail(null);//详情
        record.setCrcodeStr(null);
        record.setPayOrderid(orderId);
        String SysTraceNum = DateUtil.getSdfTimes() + Tools.getRandomNum(4);
        record.setTransNo(SysTraceNum); //交易流水号

        PayResult payResult = walletService.updatePayConsumption(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId(), actualTranAmt, orderId, payPwd, MerchantId, orderId);
        if (!payResult.getRespCode().equals("0000")) {
            throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
        }

        System.out.println("-----------------------交易手续费" + payResult.getMerchantFee());

        if (prePurchaseActivity != null) {
            //当前 处于预采购
            finishProcessPrePurchase(record);
        } else {
            record.setDividableAmount(SysUtils.Object2Integer(payResult.getMerchantFee()));//可分润金额
            record.setFee(SysUtils.Object2Integer(payResult.getMerchantFee()));
            record.setShopFee(payResult.getMerchantFee() == null ? 0 : Integer.valueOf(payResult.getMerchantFee()));

        }

        record.setTransOrderNo(payResult.getOrderId());
        record.setPayOrderid(payResult.getOrderId());
        tradeOfflineMapper.insertSelective(record);
        if (record.getReceiverType() == CommonEnum.UserType.Store.getType()) {
            posApiService.memberShopRelation(member.getId(), shop.getId(), record.getGmtCreate(), record.getOrderAmount());
        }
        posApiService.saveSynNewBenefitCalc(shop.getId(), record.getRealAmount(), record.getGroupId(), member, payResult.getOrderId(), record.getId());
        return Response.getSuccessExtend("支付成功", record);

    }

    @Override
    public void checkUserShopOrderStatus(String phone, String deskcardId, String deskcardCode) {

        if (StringUtils.isNotBlank(phone)) {
            Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
            Member member = selectMemberInfo(device.getGroupId(), phone, null);
            if (member == null) {
                return;
            }
            //查询 这个用户 台卡的未支付的交易记录
            List<TradeOffline> tradeOfflines = tradeOfflineMapper.selectTradeListByMemberAndSubType(member.getId(),
                    CommonEnum.UserType.User.getType(), PaymentScene.DeskCard.getType(), TransactionStatus.WaitingForPay.getType());

            for (TradeOffline tradeOffline : tradeOfflines) {
                //解锁优惠券
                couponUserMapper.updateUnlockCouponOnMember(tradeOffline.getOrderId());
                couponUserMapper.updateUnlockCouponOnNoMember(tradeOffline.getOrderId());

                bonusVerifyLogMapper.updateStatusByOrderId(tradeOffline.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());
                memberMapper.updateMemberBonusUnlock(tradeOffline.getPayerId(), tradeOffline.getBonusAmount());
                tradeOffline.setGmtModified(new Date());
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            }

        }
    }


    @Override
    public Response updatefyScanCodePay(String authCode, Integer realAmount, String groupId, String mchCreateIp,
                                        String notifyUrl) throws ApplicationException {

        GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(Long.valueOf(groupId));
        if (groupReceiveInfo == null) {
            return Response.getError("收款商户未配置");
        }
        String merchantNo = groupReceiveInfo.getMerchantCode();

        Group group = groupMapper.selectByPrimaryKey(Long.valueOf(groupId));
        if (group == null) {
            return Response.getError("商户信息不存在");
        }

        String orderId = UtilFun.createOrderNum(Const.TK_TICK);
        String term_id = "000000";
        Integer codetype = Integer.valueOf(authCode.substring(0, 2));
        String type = null;

        TradeOffline tradeOffline = new TradeOffline();
        if (codetype < 16) {
            type = "WECHAT";
            tradeOffline.setPayType((byte) BizEnum.PaymentType.WebChat.getType());// 支付方式
        } else {
            tradeOffline.setPayType((byte) BizEnum.PaymentType.AliPay.getType());// 支付方式
            type = "ALIPAY";
        }
        Date date = new Date();
        tradeOffline.setGmtCreate(date);
        tradeOffline.setGmtModified(date);
        tradeOffline.setGroupId(Long.valueOf(groupId));
        tradeOffline.setPayerId(null);// 付款者id号
        tradeOffline.setPayerName(null);// 付款者姓名
        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverId(group.getId() + "");// 接收者id
        tradeOffline.setReceiverName(group.getMerchantName());// 接收者 此处以核销录入数据
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());// 交易类型
        tradeOffline.setSubType((byte) BizEnum.PaymentScene.Scan.getType());// 支付场景
        tradeOffline.setOrderAmount(realAmount); // 订单金额
        tradeOffline.setDiscountAmount(0);// 折扣金额
        tradeOffline.setRealAmount(realAmount);// 实付金额

        tradeOffline.setIsWallet(false);
        tradeOffline.setGoodType(null);// 商品类型(线上用) ？
        tradeOffline.setMemo("富友面对面收款用户被扫");
        tradeOffline.setDetail("森林公园门票购买");
        tradeOffline.setMerchantNo(merchantNo);// 商户号(对账用)
        tradeOffline.setTerminalNo(term_id);// 商户终端号
        tradeOffline.setPayAccount(null);// 支付卡号
        tradeOffline.setScanOrganization(null);// 扫码付入网机构
        tradeOffline.setCrcodeStr(null);
        tradeOffline.setOldOrderId(null);
        tradeOffline.setDividableAmount(0);// 可分润金额
        tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        tradeOffline.setPayBakOrderid(null);
        tradeOffline.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());//入网机构
        tradeOffline.setOrderId(orderId);
        tradeOffline.setPayOrderid(null);//设置为空  回调的时候修改好
        tradeOffline.setFee(0);
        tradeOffline.setIsClearing(0);


        FyBeResult fyBeResult = IPayAPI.fyBePay(type, merchantNo, authCode, realAmount + "", orderId, "森林公园门票购买", "森林公园门票购买", mchCreateIp, term_id, notifyUrl);


        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (fyBeResult.getResult_code().equals("000000")) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
            tradeOffline.setTransOrderNo(fyBeResult.getMchnt_order_no());//支付机构订单号
            tradeOfflineMapper.insertSelective(tradeOffline);
            //插入服务商品订单
            OrderServiceGood orderServiceGood = new OrderServiceGood();
            orderServiceGood.setGroupId(Long.valueOf(groupId));
            orderServiceGood.setOrderNo(orderId);
            //    orderServiceGood.setNumber(realAmount.shortValue());
            orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
            orderServiceGood.setSalePrice(realAmount);
            orderServiceGood.setPromotionPrice(realAmount);
            orderServiceGood.setGoodName("门票");
            orderServiceGood.setPayTime(date);
            orderServiceGood.setGmtCreate(date);
            orderServiceGood.setGmtModified(date);
            //     orderServiceGood.setTickName(orderInDTO.getTickName());//门票名称多个用/隔开
            orderServiceGoodMapper.insertSelective(orderServiceGood);
            //插入明细
            OrderServiceGoodDetail orderServiceGoodDetail = new OrderServiceGoodDetail();
            orderServiceGoodDetail.setOrderId(orderServiceGood.getId());
            orderServiceGoodDetail.setCouponCode("000000000000");//生成券码
            orderServiceGoodDetail.setPrice(realAmount);
            orderServiceGoodDetail.setOriginalPrice(realAmount);
            orderServiceGoodDetail.setSettingPrice(0);
            orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.UnVerified.getType());
            orderServiceGoodDetail.setGmtCreate(date);
            orderServiceGoodDetail.setGmtModified(date);
            //   orderServiceGoodDetail.setOperator(orderInDTO.getOperator());
            orderServiceGoodDetail.setIsSetted(true);
            orderServiceGoodDetailMapper.insertSelective(orderServiceGoodDetail);

            resultMap.put("result_msg", fyBeResult.getResult_msg());
            resultMap.put("qr_code", fyBeResult.getResult_code());
            resultMap.put("orderId", orderId);
            resultMap.put("paytype", type);
            return Response.getSuccess(resultMap);

        } else if (fyBeResult.getResult_code().equals("030010")) {//需要输入支付密码
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());// 交易状态
            tradeOffline.setTransOrderNo(fyBeResult.getMchnt_order_no());//支付机构订单号
            tradeOfflineMapper.insertSelective(tradeOffline);

            resultMap.put("result_msg", fyBeResult.getResult_msg());
            resultMap.put("qr_code", fyBeResult.getResult_code());
            resultMap.put("orderId", orderId);
            resultMap.put("paytype", type);
            return Response.getSuccess(resultMap);

        } else {
            throw new ApplicationException(fyBeResult.getResult_msg());
        }


    }

    @Override
    public Response updatefyScanCodeQuery(String orderId) throws ApplicationException {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderId);

        if (tradeOffline == null) {
            return Response.getError("未查询到该笔订单");
        } else if (tradeOffline.getTransactionStatus().equals((byte) BizEnum.TransactionStatus.Success.getType())) {
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            resultMap.put("qr_code", "000000");
            resultMap.put("result_msg", "该笔订单已经成功支付");
            return Response.getSuccess(resultMap);
        } else {
            String order_type = null;
            if (tradeOffline.getPayType().equals((byte) BizEnum.PaymentType.WebChat.getType())) {
                order_type = "WECHAT";
            } else {
                order_type = "ALIPAY";
            }
            FyBeQueryResult result = IPayAPI.fyBeQuery(order_type, tradeOffline.getMerchantNo(),
                    tradeOffline.getTransOrderNo(), "000000");// TransOrderNo

            if (result.getResult_code().equals("000000")) {
                if (result.getResult_msg().equals("SUCCESS")) {
                    tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
                    tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                    Date date = new Date();
                    Integer realAmount = tradeOffline.getRealAmount();
                    //插入服务商品订单  setRealAmount
                    OrderServiceGood orderServiceGood = new OrderServiceGood();
                    orderServiceGood.setGroupId(tradeOffline.getGroupId());
                    orderServiceGood.setOrderNo(orderId);
                    //        orderServiceGood.setNumber(realAmount.shortValue());
                    orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
                    orderServiceGood.setSalePrice(realAmount);
                    orderServiceGood.setPromotionPrice(realAmount);
                    orderServiceGood.setGoodName("门票");
                    orderServiceGood.setPayTime(date);
                    orderServiceGood.setGmtCreate(date);
                    orderServiceGood.setGmtModified(date);
                    //     orderServiceGood.setTickName(orderInDTO.getTickName());//门票名称多个用/隔开
                    orderServiceGoodMapper.insertSelective(orderServiceGood);
                    //插入明细
                    OrderServiceGoodDetail orderServiceGoodDetail = new OrderServiceGoodDetail();
                    orderServiceGoodDetail.setOrderId(orderServiceGood.getId());
                    orderServiceGoodDetail.setCouponCode("000000000000");//生成券码
                    orderServiceGoodDetail.setPrice(realAmount);
                    orderServiceGoodDetail.setOriginalPrice(realAmount);
                    orderServiceGoodDetail.setSettingPrice(realAmount);
                    orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.UnVerified.getType());
                    orderServiceGoodDetail.setGmtCreate(date);
                    orderServiceGoodDetail.setGmtModified(date);
                    //   orderServiceGoodDetail.setOperator(orderInDTO.getOperator());
                    orderServiceGoodDetail.setIsSetted(true);
                    orderServiceGoodDetailMapper.insertSelective(orderServiceGoodDetail);

                    resultMap.put("qr_code", "000000");
                    resultMap.put("result_msg", result.getResult_msg());
                    return Response.getSuccess(resultMap);
                } else {
                    resultMap.put("qr_code", "030010");
                    resultMap.put("result_msg", result.getResult_msg());
                    return Response.getSuccess(resultMap);
                }
            } else {
                return Response.getError(result.getResult_msg());
            }
        }

    }

    //洗衣机系列方法 start
    @Override
    public Response updateXyjTkPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String shortId, String remark, String boardid,
                                   String openId, Integer actualTranAmt, Integer nooffertranAmt, String couponCodes, Integer bonusAmount, String rootHomeUrl, Integer washtype)
            throws ApplicationException {

        MachineWasher machineWasher = machineWasherMapper.selectMachineByBoardId(shortId);
        if (machineWasher == null) {
            return Response.getError("未发现该洗衣机设备");
        }
        Long groupId = machineWasher.getGroupId();
        Long shopId = machineWasher.getShopid();

        GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(groupId);
        if (groupReceiveInfo == null) {
            throw new ApplicationException(Rescode.FAIL, "收款商户未配置");
        }
        String fyMerchantCD = groupReceiveInfo.getMerchantCode();


        Member member = selectMemberInfo(groupId, phone, openId);
        Integer actualMoney = tranAmt;
        Map<String, Integer> selectTranAmt = new HashMap<String, Integer>();
        if (member != null && actualTranAmt != null) {
            selectTranAmt = calActualMoney(phone, tranAmt, nooffertranAmt, couponCodes, bonusAmount, member, shopId, groupId);
            actualMoney = selectTranAmt.get("realMoney");
            if (!actualTranAmt.equals(actualMoney)) {
                throw new ApplicationException(Rescode.FAIL, "实付金额不一致" + selectTranAmt);
            }
        }
        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        // 插入线下交易表
        TradeOffline record = finishInitTradeOff(groupId, BizEnum.PaymentType.WebChat, member, shop, boardid, fyMerchantCD, null);
        //初始化金额相关
        Integer pointCoverAmount = selectTranAmt.get("pointCoverAmount");
        initTradeAmt(record, tranAmt, actualMoney, selectTranAmt.get("couponCoverMoney"), bonusAmount, pointCoverAmount);
        System.out.println("actualMoney:"+actualMoney);
        if (actualMoney == 0) {
            String orgOrderNum = UtilFun.createOrderNum(Const.TK_XYJ);
            record.setOrderId(orgOrderNum);
            record.setPayOrderid(orgOrderNum);
            return finishXyjZroeAmount(member, shop, record, phone, nooffertranAmt, couponCodes, rootHomeUrl, boardid, washtype);

        } else {
            WxTkPay wxTkPay = WxTkPay.initialize(actualMoney + "", null, mchCreateIp, phone, notifyUrl, fyMerchantCD, remark, boardid, openId, UtilFun.createOrderNum(Const.TK_XYJ));
            WxTKPayResult wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);
            if (!wxTKPayResult.getResult_code().equals("000000")) {
                throw new ApplicationException(Rescode.FAIL, "微信调用失败" + wxTKPayResult.getResult_msg());
            }
            StringBuffer detail = new StringBuffer();
            detail.append("&appId=").append(wxTKPayResult.getSdk_appid()).append("&timeStamp=").append(wxTKPayResult.getSdk_timestamp()).append("&nonceStr=")
                    .append(wxTKPayResult.getSdk_noncestr()).append("&package=").append(wxTKPayResult.getSdk_package()).append("&signType=")
                    .append(wxTKPayResult.getSdk_signtype()).append("&paySign=").append(wxTKPayResult.getSdk_paysign());
            record.setOrderId(wxTkPay.getOutOrderNum());
            record.setDetail(detail.toString());// 详情
            record.setCrcodeStr(wxTKPayResult.getQr_code());
            record.setTransOrderNo(wxTKPayResult.getMchnt_order_no());
            record.setPayOrderid(wxTkPay.getOutOrderNum());
            record.setMarked(Long.valueOf(washtype));//存洗衣机的洗衣模式
            tradeOfflineMapper.insertSelective(record);
            //锁定积分 和优惠券
            finishActualMoney(phone, couponCodes, member, shopId, groupId, nooffertranAmt, record);
            HashMap<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("appId", wxTKPayResult.getSdk_appid());
            resultMap.put("timeStamp", wxTKPayResult.getSdk_timestamp());
            resultMap.put("nonceStr", wxTKPayResult.getSdk_noncestr());
            resultMap.put("package", wxTKPayResult.getSdk_package());
            resultMap.put("signType", wxTKPayResult.getSdk_signtype());
            resultMap.put("paySign", wxTKPayResult.getSdk_paysign());
            return Response.getSuccess(resultMap);
        }

    }


    @Override
    public Response updateXyjWalletPay(Integer tranAmt, String mchCreateIp, String phone, String notifyUrl, String shortId, String remark, String boardid,
                                       String payPwd, Integer actualTranAmt, Integer nooffertranAmt, String couponCodes, Integer bonusAmount, String rootHomeUrl, Integer washtype) throws ApplicationException {
        MachineWasher machineWasher = machineWasherMapper.selectMachineByBoardId(shortId);
        if (machineWasher == null) {
            return Response.getError("未发现该洗衣机设备");
        }
        Long groupId = machineWasher.getGroupId();
        Long shopId = machineWasher.getShopid();

        Member member = null;
        if (StringUtils.isNotBlank(phone)) {
            member = selectMemberInfo(groupId, phone, null);
            if (member == null) {
                return Response.getError("您输入的手机号没有查询到会员，请确认是否正确");
            }
        }
        if (member == null) {
            return Response.getError("会员信息不存在");
        }
        if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
            return Response.getError("支付密码错误");
        }

        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(groupId, shop.getId());
        if (shopGroupRelation == null) {
            throw new ApplicationException(Rescode.FAIL, "商户配置信息不存在");
        }

        Map<String, Integer> selectTranAmt = calActualMoney(phone, tranAmt, nooffertranAmt, couponCodes, bonusAmount, member, shopId, groupId);
        Integer actualMoney = selectTranAmt.get("realMoney");
        if (!actualTranAmt.equals(actualMoney)) {
            throw new ApplicationException(Rescode.FAIL, "实付金额不一致" + selectTranAmt);
        }
        String orgOrderNum = UtilFun.createOrderNum(Const.TK_XYJ);
        String MerchantId = shopGroupRelation.getPayMerchantCode();
        //   TradeOffline record=finishInitTradeOff(groupId,BizEnum.PaymentType.Wallet,member, shop,deskcardCode, MerchantId,  deviceDeskCard);
        TradeOffline record = finishInitTradeOff(groupId, BizEnum.PaymentType.Wallet, member, shop, boardid, MerchantId, null);
        //初始化金额相关
        Integer pointCoverAmount = selectTranAmt.get("pointCoverAmount");
        initTradeAmt(record, tranAmt, actualMoney, selectTranAmt.get("couponCoverMoney"), bonusAmount, pointCoverAmount);
        record.setCheckStatus(0);
        if (actualMoney == 0) {
            record.setOrderId(orgOrderNum);
            record.setPayOrderid(orgOrderNum);
            return finishXyjZroeAmount(member, shop, record, phone, nooffertranAmt, couponCodes, rootHomeUrl, boardid, washtype);

        } else {
            record.setTransNo(DateUtil.getSdfTimes() + Tools.getRandomNum(4)); //交易流水号
            String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();
            PayResult payResult = walletService.updatePayConsumption(member.getVirtualCard(), payGroupCode, member.getUserId(), actualTranAmt, orgOrderNum, payPwd, MerchantId, orgOrderNum);
            if (!payResult.getRespCode().equals("0000")) {
                throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
            }
            logger.info("-----------------------钱包交易手续费" + payResult.getMerchantFee());
            record.setDividableAmount(SysUtils.Object2Integer(payResult.getMerchantFee()));//可分润金额
            record.setFee(SysUtils.Object2Integer(payResult.getMerchantFee()));
            record.setShopFee(Tools.isEmpty(payResult.getMerchantFee()) ? 0 : Integer.valueOf(payResult.getMerchantFee()));
            record.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            record.setTransOrderNo(payResult.getOrderId());
            record.setPayOrderid(orgOrderNum);
            record.setOrderId(orgOrderNum);
            tradeOfflineMapper.insertSelective(record);
        }
        //锁定积分和优惠券
        finishActualMoney(phone, couponCodes, member, shopId, groupId, nooffertranAmt, record);
        //完成 积分和优惠券的核销  replace
        posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(record, couponCodes, shop.getId());
        if (record.getReceiverType() == CommonEnum.UserType.Store.getType()) {
            posApiService.memberShopRelation(member.getId(), shop.getId(), record.getGmtCreate(), record.getOrderAmount());
        }
        posApiService.saveSynNewBenefitCalc(shop.getId(), record.getRealAmount(), record.getGroupId(), member, record.getPayOrderid(), record.getId());
        logger.info("--准备发送模板消息--");
        try {
            templateMailSendService.sendTemplate(record, BizEnum.WebTemplateType.template11.getType(), record.getPayerId(),
                    record.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("--模板消息发送失败--" + e);
        }

        final String memberid = member.getId() + "";
        //异步发送指令
        exec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!IPayAPI.sendCommand("start", boardid, washtype + "", memberid, orgOrderNum)) {//执行失败
                        //微信发送模板消息
                        if (record.getPayerId() != null) {
                            try {
                                templateMailSendService.sendTemplate(record, BizEnum.WebTemplateType.template5.getType(),
                                        record.getPayerId(),
                                        record.getGroupId(), BizEnum.PaymentType.WebChat.getType(), ROOT_HOME_URL);
                            } catch (Exception e) {
                                logger.info("模板消息发送失败" + e);
                            }
                        }
                        System.out.println("start8:" + System.currentTimeMillis());
                        //退款
                        posApiService.refundBenefit(record, record.getTransOrderNo());
                        posApiServiceTransactional.saveOtherRefund(record.getTransOrderNo(),
                                null, record.getPayType() != null ? record.getPayType() : 0,
                                record);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


        Response response = Response.getSuccessExtend("支付成功", record);
        return response;
    }

    @Override
    public void checkXyjUserShopOrderStatus(String phone, String shortId) {
        if (StringUtils.isNotBlank(phone)) {
            MachineWasher machineWasher = machineWasherMapper.selectMachineByBoardId(shortId);
            if (machineWasher == null) {
                return;
            }
            Member member = selectMemberInfo(machineWasher.getGroupId(), phone, null);
            if (member == null) {
                return;
            }
            //查询 这个用户 台卡的未支付的交易记录
            List<TradeOffline> tradeOfflines = tradeOfflineMapper.selectTradeListByMemberAndSubType(member.getId(),
                    CommonEnum.UserType.User.getType(), PaymentScene.DeskCard.getType(), TransactionStatus.WaitingForPay.getType());

            for (TradeOffline tradeOffline : tradeOfflines) {
                //解锁优惠券
                couponUserMapper.updateUnlockCouponOnMember(tradeOffline.getOrderId());
                couponUserMapper.updateUnlockCouponOnNoMember(tradeOffline.getOrderId());

                bonusVerifyLogMapper.updateStatusByOrderId(tradeOffline.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());
                memberMapper.updateMemberBonusUnlock(tradeOffline.getPayerId(), tradeOffline.getBonusAmount());
                tradeOffline.setGmtModified(new Date());
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            }

        }

    }

    //洗衣机无需支付的时候
    private Response finishXyjZroeAmount(Member member, Shop shop, TradeOffline record, String phone, Integer nooffertranAmt, String couponCodes, String rootHomeUrl, String boardid, int washtype) throws ApplicationException {
        try {
            //锁定积分
            record.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());

            tradeOfflineMapper.insertSelective(record);

            //锁定积分和优惠券
            finishActualMoney(phone, couponCodes, member, shop.getId(), member.getGroupId(), nooffertranAmt, record);
            //完成 积分和优惠券的核销
            posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(record, couponCodes, shop.getId());
        } catch (ApplicationException e1) {

            e1.printStackTrace();
            throw e1;
        }

        //会员门店关系
        posApiService.memberShopRelation(member.getId(), shop.getId(), new Date(), record.getOrderAmount());
        //计算新的会员权益
        posApiService.saveSynNewBenefitCalc(shop.getId(), record.getRealAmount(), member.getGroupId(), member, record.getPayOrderid(), record.getId());

        //异步发送洗衣机指令
        exec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!IPayAPI.sendCommand("start", boardid, washtype + "", member.getId() + "", record.getOrderId())) {
                        //微信发送模板消息
                        if (record.getPayerId() != null) {
                            try {
                                templateMailSendService.sendTemplate(record, BizEnum.WebTemplateType.template5.getType(),
                                        record.getPayerId(),
                                        record.getGroupId(), BizEnum.PaymentType.WebChat.getType(), ROOT_HOME_URL);
                            } catch (Exception e) {
                                logger.info("模板消息发送失败" + e);
                            }
                        }
                        //退款
                        posApiService.refundBenefit(record, record.getTransOrderNo());
                        posApiServiceTransactional.saveOtherRefund(record.getTransOrderNo(),
                                null, record.getPayType() != null ? record.getPayType() : 0,
                                record);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        try {
            templateMailSendService.sendTemplate(record, BizEnum.WebTemplateType.template11.getType(), record.getPayerId(),
                    record.getGroupId(), BizEnum.PaymentType.Wallet.getType(), rootHomeUrl);
        } catch (Exception e) {
            logger.info("模板消息发送失败" + e);
        }
        //return Response.getSuccess(2, "支付成功");
        return Response.getSuccessExtend("支付成功", record);
    }
    //洗衣机系列方法 end


}
